diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 795136609dc0a..f7bf53b67552a 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -938,7 +938,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_parameter_0_has_a_circular_constraint_2313": "Der Typparameter \"{0}\" weist eine zirkuläre Einschränkung auf.", - "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" weist einen zirkulären Standard auf.", + "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" besitzt einen zirkulären Standardwert.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Der Typparameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Der Typparameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Der Typparameter \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 2c93bcf114d47..39be2d5b40484 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -135,9 +135,9 @@ - + - + @@ -861,6 +861,18 @@ + + + + + + + + + + + + @@ -1233,6 +1245,12 @@ + + + + + + @@ -1401,6 +1419,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2001,6 +2049,18 @@ + + + + + + + + + + + + @@ -2349,6 +2409,12 @@ + + + + + + @@ -2421,9 +2487,9 @@ - + - + @@ -2781,6 +2847,18 @@ + + + + + + + + + + + + @@ -2829,12 +2907,6 @@ - - - - - - @@ -3045,6 +3117,12 @@ + + + + + + @@ -3225,6 +3303,12 @@ + + + + + + @@ -3705,6 +3789,12 @@ + + + + + + @@ -3909,9 +3999,9 @@ - + - + @@ -5025,12 +5115,6 @@ - - - - - - @@ -5313,6 +5397,12 @@ + + + + + + @@ -5589,6 +5679,12 @@ + + + + + + @@ -6051,6 +6147,12 @@ + + + + + + @@ -6207,6 +6309,12 @@ + + + + + + @@ -6393,6 +6501,12 @@ + + + + + + @@ -6657,12 +6771,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -6831,6 +6969,18 @@ + + + + + + + + + + + + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 0e0e31a2b1131..52840b1208e1c 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -328,7 +328,7 @@ "Do_not_emit_outputs_if_any_errors_were_reported_6008": "No emitir salidas si se informa de algún error.", "Do_not_emit_use_strict_directives_in_module_output_6112": "No emitir directivas 'use strict' en la salida del módulo.", "Do_not_erase_const_enum_declarations_in_generated_code_6007": "No borrar las declaraciones de enumeración const en el código generado.", - "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones auxiliares personalizadas como \"__extends\" en la salida compilada.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones del asistente personalizadas como \"__extends\" en la salida compilada.", "Do_not_include_the_default_library_file_lib_d_ts_6158": "No incluir el archivo de biblioteca predeterminado (lib.d.ts).", "Do_not_report_errors_on_unreachable_code_6077": "No notificar los errores del código inaccesible.", "Do_not_report_errors_on_unused_labels_6074": "No notificar los errores de las etiquetas no usadas.", @@ -477,7 +477,7 @@ "Import_declaration_0_is_using_private_name_1_4000": "La declaración de importación '{0}' usa el nombre privado '{1}'.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La declaración de importación está en conflicto con la declaración local de \"{0}\".", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Las declaraciones de importación de un espacio de nombres no pueden hacer referencia a un módulo.", - "Import_emit_helpers_from_tslib_6139": "Importe elementos auxiliares de emisión de \"tslib\".", + "Import_emit_helpers_from_tslib_6139": "Importe asistentes de emisión de \"tslib\".", "Import_may_be_converted_to_a_default_import_80003": "La importación puede convertirse a una importación predeterminada.", "Import_name_cannot_be_0_2438": "El nombre de importación no puede ser \"{0}\".", "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La declaración de importación o exportación de una declaración de módulo de ambiente no puede hacer referencia al módulo a través de su nombre relativo.", @@ -892,8 +892,8 @@ "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La declaración de variable de una instrucción \"for...of\" no puede tener un inicializador.", "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "No se admite la instrucción 'with'. Todos los símbolos de un bloque 'with' tendrán el tipo 'any'.", "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta función de constructor puede convertirse en una declaración de clase.", - "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere una aplicación auxiliar importada, pero no se puede encontrar el módulo \"{0}\".", - "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere una aplicación auxiliar importada denominada \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere un asistente importado, pero no se puede encontrar el módulo \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere un asistente importado denominado \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", "Trailing_comma_not_allowed_1009": "No se permite la coma final.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilar cada archivo como un módulo aparte (parecido a \"ts.transpileModule\").", "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Pruebe \"npm install @types/{0}\" si existe o agregue un nuevo archivo de declaración (.d.ts) que incluya \"declare module '{0}';\"", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index c5d6cf984db76..1003d62329ccb 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -68,7 +68,7 @@ "A_rest_parameter_cannot_have_an_initializer_1048": "rest 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 매개 변수는 매개 변수 목록 마지막에 있어야 합니다.", "A_rest_parameter_must_be_of_an_array_type_2370": "rest 매개 변수는 배열 형식이어야 합니다.", - "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표를 사용할 수 없습니다.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표가 없을 수 있습니다.", "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 문은 함수 본문 내에서만 사용할 수 있습니다.", "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "가져오기를 'baseUrl'에 상대적인 조회 위치로 다시 매핑하는 일련의 항목입니다.", "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 접근자에는 반환 형식 주석을 사용할 수 없습니다.", @@ -232,7 +232,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", - "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' 집합이 없기 때문에 '{0}' 프로젝트를 추가할 수 없습니다.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' 프로젝트는 'outFile'이 설정되어 있지 않기 때문에 앞에 추가할 수 없습니다.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.", "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", @@ -274,7 +274,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.", "Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.", "Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", - "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 사용하지 않도록 설정할 수 없습니다.", + "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 비활성화할 수 없습니다.", "Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.", "Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.", @@ -445,7 +445,7 @@ "Function_overload_must_be_static_2387": "함수 오버로드는 정적이어야 합니다.", "Function_overload_must_not_be_static_2388": "함수 오버로드는 정적이 아니어야 합니다.", "Generate_get_and_set_accessors_95046": "'get' 및 'set' 접근자 생성", - "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "해당하는 각 '.d.ts' 파일의 sourcemap을 생성합니다.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "해당하는 각 '.d.ts' 파일에 sourcemap을 생성합니다.", "Generates_corresponding_d_ts_file_6002": "해당 '.d.ts' 파일을 생성합니다.", "Generates_corresponding_map_file_6043": "해당 '.map' 파일을 생성합니다.", "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "생성기는 값을 생성하지 않으므로 암시적으로 '{0}' 형식입니다. 반환 형식을 제공하세요.", @@ -677,13 +677,13 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", "Print_this_message_6017": "이 메시지를 출력합니다.", - "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{1}' 종속성에 오류가 있기 때문에 '{0}' 프로젝트를 빌드할 수 없습니다.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{0}' 프로젝트는 '{1}' 종속성에 오류가 있기 때문에 빌드할 수 없습니다.", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{1}' 종속성이 최신 상태가 아니기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "가장 오래된 출력 '{1}'이(가) 최신 입력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "'{1}' 출력 파일이 존재하지 않기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_up_to_date_6361": "'{0}' 프로젝트가 최신 상태입니다.", "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "최신 입력 '{1}'이(가) 가장 오래된 출력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태입니다.", - "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "종속성의 .d.ts 파일이 있기 때문에 '{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' 프로젝트는 종속성에 .d.ts 파일이 있는 최신 상태입니다.", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", "Projects_in_this_build_Colon_0_6355": "이 빌드의 프로젝트: {0}", "Projects_to_reference_6300": "참조할 프로젝트", @@ -803,7 +803,7 @@ "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "빌드될 항목 표시(또는 '--clean'으로 지정된 경우 삭제될 항목 표시)", "Signature_0_must_be_a_type_predicate_1224": "'{0}' 시그니처는 형식 조건자여야 합니다.", "Skip_type_checking_of_declaration_files_6012": "선언 파일 형식 검사를 건너뜁니다.", - "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{1}' 종속성에 오류가 있기 때문에 '{0}' 프로젝트 빌드를 건너뜁니다.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{0}' 프로젝트의 빌드는 '{1}' 종속성에 오류가 있기 때문에 건너뜁니다.", "Skipping_clean_because_not_all_projects_could_be_located_6371": "일부 프로젝트를 찾을 수 없으므로 정리를 건너뛰는 중입니다.", "Source_Map_Options_6175": "소스 맵 옵션", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "특수화된 오버로드 시그니처는 특수화되지 않은 서명에 할당할 수 없습니다.", @@ -1039,7 +1039,7 @@ "const_declarations_must_be_initialized_1155": "'const' 선언은 초기화해야 합니다.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 열거형 멤버 이니셜라이저가 무한 값에 대해 평가되었습니다.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 열거형 멤버 이니셜라이저가 허용되지 않은 'NaN' 값에 대해 평가되었습니다.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽 또는 형식 쿼리에서만 사용할 수 있습니다.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성이나 인덱스 액세스 식, 또는 내보내기 할당이나 가져오기 선언의 오른쪽, 또는 형식 쿼리에서만 사용할 수 있습니다.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "이 항목 삭제 - '{0}' 프로젝트는 이전에 빌드되었기 때문에 최신 상태입니다.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum 선언'은 .ts 파일에서만 사용할 수 있습니다.", diff --git a/lib/lib.es2015.promise.d.ts b/lib/lib.es2015.promise.d.ts index 9f27b7b59ab8c..002d69165fdd7 100644 --- a/lib/lib.es2015.promise.d.ts +++ b/lib/lib.es2015.promise.d.ts @@ -27,7 +27,7 @@ interface PromiseConstructor { /** * Creates a new Promise. * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * a resolve callback used to resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; @@ -213,4 +213,4 @@ interface PromiseConstructor { resolve(): Promise; } -declare var Promise: PromiseConstructor; \ No newline at end of file +declare var Promise: PromiseConstructor; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 840fd68278906..02f6f82971e0f 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1398,6 +1398,16 @@ type Extract = T extends U ? T : never; */ type NonNullable = T extends null | undefined ? never : T; +/** + * Obtain the parameters of a function type in a tuple + */ +type Parameters any> = T extends (...args: infer P) => any ? P : never; + +/** + * Obtain the parameters of a constructor function type in a tuple + */ +type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; + /** * Obtain the return type of a function type */ diff --git a/lib/lib.esnext.array.d.ts b/lib/lib.esnext.array.d.ts index 3da8562d2ea50..6c75122320954 100644 --- a/lib/lib.esnext.array.d.ts +++ b/lib/lib.esnext.array.d.ts @@ -31,7 +31,7 @@ interface ReadonlyArray { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] @@ -145,7 +145,7 @@ interface Array { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index e7fcfc6ff5dd8..5d82f7c1c9a1b 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -832,6 +832,11 @@ declare namespace ts.server.protocol { * True if item can be renamed. */ canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; /** * Error message if item can not be renamed. */ @@ -852,6 +857,8 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; } /** * A group of text spans, all in 'file'. @@ -1373,7 +1380,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions; + command: CommandTypes.Completions | CommandTypes.CompletionInfo; arguments: CompletionsRequestArgs; } /** @@ -1885,6 +1892,15 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } type LargeFileReferencedEventName = "largeFileReferenced"; interface LargeFileReferencedEvent extends Event { event: LargeFileReferencedEventName; @@ -2220,6 +2236,7 @@ declare namespace ts.server.protocol { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index 509172c0ead8b..de74fa7bdcd07 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -61,7 +61,7 @@ "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Uma propriedade de uma interface ou tipo literal cujo tipo é um tipo de 'unique symbol' deve ser 'readonly'.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Um parâmetro obrigatório não pode seguir um parâmetro opcional.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Um elemento rest não pode conter um padrão de associação.", - "A_rest_element_cannot_have_a_property_name_2566": "Um elemento restante não pode ter um nome de propriedade.", + "A_rest_element_cannot_have_a_property_name_2566": "Um elemento rest não pode ter um nome de propriedade.", "A_rest_element_cannot_have_an_initializer_1186": "Um elemento rest não pode ter um inicializador.", "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Um elemento rest deve ser o último em um padrão de desestruturação.", "A_rest_parameter_cannot_be_optional_1047": "Um parâmetro rest não pode ser opcional.", @@ -174,7 +174,7 @@ "An_object_member_cannot_be_declared_optional_1162": "Um membro de objeto não pode ser declarado como opcional.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "A assinatura de sobrecarga não pode ser declarada como geradora.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Uma expressão unária com o operador '{0}' não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", - "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos de JSDoc", + "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos do JSDoc", "Annotate_with_type_from_JSDoc_95009": "Anotar com o tipo do JSDoc", "Annotate_with_types_from_JSDoc_95010": "Anotar com os tipos do JSDoc", "Argument_expression_expected_1135": "Expressão de argumento esperada.", @@ -368,7 +368,7 @@ "Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.", "Enum_0_used_before_its_declaration_2450": "A enumeração '{0}' usada antes de sua declaração.", - "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações de enum apenas podem se mescladas com namespaces ou com outras declarações de enum.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações enum só podem ser mescladas com namespaces ou com outras declarações enum.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações de enumeração devem ser const ou não const.", "Enum_member_expected_1132": "Membro de enumeração esperado.", "Enum_member_must_have_initializer_1061": "O membro de enumeração deve ter um inicializador.", @@ -571,7 +571,7 @@ "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "O módulo {0} já exportou um membro denominado '{1}'. Considere reexportar explicitamente para resolver a ambiguidade.", "Module_0_has_no_default_export_1192": "O módulo '{0}' não tem padrão de exportação.", "Module_0_has_no_exported_member_1_2305": "O módulo '{0}' não tem nenhum membro exportado '{1}'.", - "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro exportado '{1}'. Você quis dizer '{2}'?", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro '{1}' exportado. Você quis dizer '{2}'?", "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "O módulo '{0}' está oculto por uma declaração de local com o mesmo nome.", "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "O módulo '{0}' resolve para uma entidade sem módulo e não pode ser importado usando este constructo.", "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "O módulo '{0}' usa 'export =' e não pode ser usado com 'export *'.", @@ -622,7 +622,7 @@ "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "A opção '{0} só pode ser usada quando qualquer uma das opções '--inlineSourceMap' ou '--sourceMap' é fornecida.", "Option_0_cannot_be_specified_with_option_1_5053": "A opção '{0}' não pode ser especificada com a opção '{1}'.", "Option_0_cannot_be_specified_without_specifying_option_1_5052": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}'.", - "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}' ou a opção '{2}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem a especificação da opção '{1}' ou '{2}'.", "Option_0_should_have_array_of_strings_as_a_value_6103": "A opção '{0}' deve ter matriz de cadeias de um valor.", "Option_build_must_be_the_first_command_line_argument_6369": "A opção '--build' precisa ser o primeiro argumento da linha de comando.", "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "A opção 'isolatedModules' só pode ser usada quando nenhuma opção de '--module' for fornecida ou a opção 'target' for 'ES2015' ou superior.", @@ -686,7 +686,7 @@ "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "O projeto '{0}' está atualizado com os arquivos .d.ts de suas dependências", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}", "Projects_in_this_build_Colon_0_6355": "Projetos neste build: {0}", - "Projects_to_reference_6300": "Projetos para referência", + "Projects_to_reference_6300": "Projetos a serem referenciados", "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "A propriedade '{0}' não existe no tipo '{1}'. Você esqueceu de usar 'await'?", @@ -740,7 +740,7 @@ "Remove_braces_from_arrow_function_95060": "Remover chaves da função de seta", "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", "Remove_destructuring_90009": "Remover desestruturação", - "Remove_import_from_0_90005": "Remover importação do '{0}'", + "Remove_import_from_0_90005": "Remover importação de '{0}'", "Remove_unreachable_code_95050": "Remover código inacessível", "Remove_unused_label_95053": "Remover rótulo não utilizado", "Remove_variable_statement_90010": "Remover instrução de variável", @@ -752,7 +752,7 @@ "Report_errors_on_unused_parameters_6135": "Relatar erros nos parâmetros não utilizados.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Os parâmetros de tipo necessários podem não seguir os parâmetros de tipo opcionais.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "A resolução para o módulo '{0}' foi encontrada no cache do local '{1}'.", - "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' para nomes de propriedades com valores de cadeia de caracteres somente (sem números ou símbolos).", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' somente para nomes de propriedades com valores de cadeia de caracteres (sem números nem símbolos).", "Resolving_from_node_modules_folder_6118": "Resolvendo na pasta node_modules...", "Resolving_module_0_from_1_6086": "======== Resolvendo módulo '{0}' de '{1}'. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolvendo nome de módulo '{0}' relativo à URL base '{1}' - '{2}'.", @@ -803,8 +803,8 @@ "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostrar o que seria compilado (ou excluído, se especificado com '--clean')", "Signature_0_must_be_a_type_predicate_1224": "A assinatura '{0}' deve ser um predicado de tipo.", "Skip_type_checking_of_declaration_files_6012": "Ignorar a verificação de tipo dos arquivos de declaração.", - "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando build do projeto '{0}' porque sua dependência '{1}' tem erros", - "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque nem todos os projetos foram localizados", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando o build do projeto '{0}' porque a dependência '{1}' tem erros", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque não foram localizados todos os projetos", "Source_Map_Options_6175": "Opções do Sourcemap", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "A assinatura de sobrecarga especializada não pode ser atribuída a qualquer assinatura não especializada.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "O especificador de importação dinâmica não pode ser o elemento de difusão.", @@ -966,7 +966,7 @@ "Unexpected_end_of_text_1126": "Fim inesperado do texto.", "Unexpected_token_1012": "Token inesperado.", "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Um construtor, método, acessador ou propriedade era esperado.", - "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Um nome de parâmetro de tipo era esperado sem chaves.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Era esperado um nome de parâmetro de tipo sem chaves.", "Unexpected_token_expected_1179": "Token inesperado. '{' esperado.", "Unknown_compiler_option_0_5023": "Opção do compilador '{0}' desconhecida.", "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opção desconhecida 'excludes'. Você quis dizer 'exclude'?", @@ -993,7 +993,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "A lista de declaração de variável não pode estar vazia.", "Version_0_6029": "Versão {0}", "Watch_input_files_6005": "Observe os arquivos de entrada.", - "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se se deve manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se é necessário manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 611ccb3a4ad33..284c223d0cd0e 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -49,8 +49,8 @@ "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Bir ad alanı stili içeri aktarma işlemi çağrılamadığından veya oluşturulamadığından çalışma zamanında hataya yol açacak.", - "A_non_dry_build_would_build_project_0_6357": "non-dry bir derleme '{0}' projesini derler", - "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "non-dry bir derleme şu dosyaları siler: {0}", + "A_non_dry_build_would_build_project_0_6357": "-dry bayrağı kullanılmayan bir derleme '{0}' projesini derler", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry bayrağı kullanılmayan bir derleme şu dosyaları siler: {0}", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Parametre başlatıcısına yalnızca bir işlevde veya oluşturucu uygulamasında izin verilir.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Parametre özelliği, rest parametresi kullanılarak bildirilemez.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Parametre özelliğine yalnızca bir oluşturucu uygulamasında izin verilir.", @@ -110,7 +110,7 @@ "Add_initializers_to_all_uninitialized_properties_95027": "Tüm başlatılmamış özelliklere başlatıcılar ekle", "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", "Add_missing_typeof_95052": "Eksik 'typeof' öğesini ekle", - "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekleyin veya kaldırın", + "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekle veya kaldır", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Bir üye adıyla eşleşen tüm çözülmemiş değişkenlere niteleyici ekle", "Add_to_all_uncalled_decorators_95044": "Çağrılmayan tüm dekoratörlere '()' ekle", "Add_ts_ignore_to_all_error_messages_95042": "Tüm hata iletilerine '@ts-ignore' ekle", @@ -122,7 +122,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tüm '{0}' bildirimleri özdeş tür parametrelerine sahip olmalıdır.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", - "All_destructured_elements_are_unused_6198": "Yok edilen öğelerin hiçbiri kullanılmamış.", + "All_destructured_elements_are_unused_6198": "Yapısı bozulan öğelerin hiçbiri kullanılmıyor.", "All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.", "All_variables_are_unused_6199": "Hiçbir değişken kullanılmıyor.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", @@ -232,7 +232,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Muhtemelen 'null' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Muhtemelen 'null' veya 'undefined' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Muhtemelen 'undefined' olan bir nesne çağrılamıyor.", - "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' projesi, 'outFile' kümesi içermediğinden başa eklenemiyor", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "{0}' projesi için 'outFile' ayarlanmadığından başa eklenemiyor", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.", "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", @@ -311,7 +311,7 @@ "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekoratörler aynı ada sahip birden fazla get/set erişimcisine uygulanamaz.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Modülün varsayılan dışarı aktarımı '{0}' özel adına sahip veya bu adı kullanıyor.", "Delete_all_unused_declarations_95024": "Kullanılmayan tüm bildirimleri sil", - "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını silin", + "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını sil", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Kullanım Dışı] Bunun yerine '--jsxFactory' kullanın. 'react' JSX gösterimi hedefleniyorsa, createElement için çağrılan nesneyi belirtin", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Kullanım Dışı] Bunun yerine '--outFile' kullanın. Çıkışı tek bir dosya olarak birleştirin ve gösterin", "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Kullanım Dışı] Bunun yerine '--skipLibCheck' kullanın. Varsayılan kitaplık bildirim dosyalarının tür denetimini atlayın.", @@ -362,13 +362,13 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.", "Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.", "Enable_tracing_of_the_name_resolution_process_6085": "Ad çözümleme işlemini izlemeyi etkinleştir.", - "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştirin", + "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştir", "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Tüm içeri aktarma işlemleri için ad alanı nesnelerinin oluşturulması aracılığıyla CommonJS ile ES Modülleri arasında yayımlama birlikte çalışabilirliğine imkan tanır. Şu anlama gelir: 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Zaman uyumsuz ES7 işlevleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.", "Enum_0_used_before_its_declaration_2450": "'{0}' sabit listesi, bildiriminden önce kullanıldı.", - "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enum bildirimleri yalnızca ad alanı veya diğer enum bildirimleri ile birleştirilebilir.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Sabit listesi bildirimleri yalnızca ad alanı veya diğer sabit listesi bildirimleri ile birleştirilebilir.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Sabit listesi bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", "Enum_member_expected_1132": "Sabit listesi üyesi bekleniyor.", "Enum_member_must_have_initializer_1061": "Sabit listesi üyesi bir başlatıcıya sahip olmalıdır.", @@ -571,7 +571,7 @@ "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} modülü, '{1}' adlı bir üyeyi zaten dışarı aktardı. Belirsizliği çözmek için açık olarak yeniden dışarı aktarmayı göz önünde bulundurun.", "Module_0_has_no_default_export_1192": "'{0}' modülü için varsayılan dışarı aktarma yok.", "Module_0_has_no_exported_member_1_2305": "'{0}' modülü, dışarı aktarılan '{1}' üyesine sahip değil.", - "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "'{0}' modülünün dışa aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "{0}' modülünün dışarı aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' modülü, aynı ada sahip bir yerel bildirim tarafından gizleniyor.", "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "'{0}' modülü, modül olmayan bir varlığa çözümleniyor ve bu oluşturma ile içeri aktarılamaz.", "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "'{0}' modülü 'export =' kullanıyor ve 'export *' ile birlikte kullanılamaz.", @@ -737,7 +737,7 @@ "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.", "Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır", "Remove_all_unused_labels_95054": "Kullanılmayan tüm etiketleri kaldır", - "Remove_braces_from_arrow_function_95060": "Ok işlevinden köşeli ayraçları kaldırın", + "Remove_braces_from_arrow_function_95060": "Ok işlevinden küme ayraçlarını kaldır", "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", "Remove_destructuring_90009": "Yıkmayı kaldır", "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", diff --git a/lib/tsc.js b/lib/tsc.js index 7a7216cf020d4..02a06ade376ef 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -60,9 +60,10 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook var ts; (function (ts) { ts.versionMajorMinor = "3.1"; - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -661,16 +662,13 @@ var ts; return result; } function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -712,7 +710,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1011,7 +1009,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1125,6 +1123,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1673,6 +1675,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); var ts; (function (ts) { @@ -1732,6 +1738,287 @@ var ts; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + var Version = (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + if (this === other) + return 0; + if (other === undefined) + return 1; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + if (left === right) + return 0; + if (left.length === 0) + return right.length === 0 ? 0 : 1; + if (right.length === 0) + return -1; + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 : 1; + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + return ts.compareValues(left.length, right.length); + } + var VersionRange = (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; (function (ts) { var OperationCanceledException = (function () { function OperationCanceledException() { @@ -2048,17 +2335,20 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; function createRecursiveDirectoryWatcher(host) { var cache = ts.createMap(); var callbackCache = ts.createMultiMap(); @@ -2885,7 +3175,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -2924,6 +3214,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -3167,7 +3461,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -3195,6 +3488,13 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3286,6 +3586,8 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + Index_0_is_out_of_bounds_in_tuple_of_length_1: diag(2733, ts.DiagnosticCategory.Error, "Index_0_is_out_of_bounds_in_tuple_of_length_1_2733", "Index '{0}' is out-of-bounds in tuple of length {1}."), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -3399,7 +3701,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -3493,7 +3797,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -3591,6 +3895,14 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -3621,9 +3933,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -3688,6 +4000,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -3816,6 +4129,8 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; @@ -4418,6 +4733,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -4447,6 +4763,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -4867,6 +5184,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -4903,6 +5221,24 @@ var ts; case 11: case 12: case 32: + case 160: + case 5760: + case 8192: + case 8193: + case 8194: + case 8195: + case 8196: + case 8197: + case 8198: + case 8199: + case 8200: + case 8201: + case 8202: + case 8203: + case 8239: + case 8287: + case 12288: + case 65279: if (skipTrivia) { pos++; continue; @@ -4960,6 +5296,10 @@ var ts; return pos += 2, token = 40; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1)) { + asteriskSeen = true; + continue; + } return token = 39; case 43: if (text.charCodeAt(pos + 1) === 43) { @@ -5512,6 +5852,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -5527,7 +5870,6 @@ var ts; ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; })(ts || (ts = {})); (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -5606,22 +5948,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -5726,6 +6055,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -5901,12 +6236,19 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -5926,11 +6268,11 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216) ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: if (node.singleQuote) { @@ -6267,6 +6609,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2); } @@ -6926,18 +7272,18 @@ var ts; return node.kind === 246 && node.moduleReference.kind !== 257; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216); } @@ -6977,14 +7323,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -7007,14 +7353,18 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -7022,20 +7372,20 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - function getDeclaredJavascriptInitializer(node) { + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; - function getAssignedJavascriptInitializer(node) { + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 || e.kind === 195 ? initializer : undefined; @@ -7049,21 +7399,21 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + ts.getExpandoInitializer = getExpandoInitializer; + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 && ts.isIdentifier(parent.left)) { @@ -7074,7 +7424,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; function isSameEntityName(name, initializer) { if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { return name.escapedText === initializer.escapedText; @@ -7107,12 +7457,12 @@ var ts; return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 || isInJavaScriptFile(expr) ? special : 0; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 || isInJSFile(expr) ? special : 0; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 || !ts.isPropertyAccessExpression(expr.left)) { return 0; @@ -7121,9 +7471,9 @@ var ts; if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { return 6; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99) { return 4; } @@ -7148,7 +7498,7 @@ var ts; } return 0; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -7157,11 +7507,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 && !!ts.getJSDocTypeTag(expr.parent); } @@ -7267,7 +7617,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 && + getAssignmentDeclarationKind(node.expression) !== 0 && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 ? node.expression.right.right @@ -7308,6 +7658,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -7477,6 +7831,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193) { + node = node.parent; + } + return node; + } function isDeleteTarget(node) { if (node.kind !== 187 && node.kind !== 188) { return false; @@ -7498,32 +7858,35 @@ var ts; return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71: case 9: - case 8: { - var parent = name.parent; + case 8: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + case 71: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 && + getAssignmentDeclarationKind(binExp) !== 0 && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 147 && @@ -7569,7 +7932,7 @@ var ts; node.kind === 251 || node.kind === 255 || node.kind === 252 && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -7578,7 +7941,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { var tag = ts.getJSDocAugmentsTag(node); if (tag) { return tag.class; @@ -8263,7 +8626,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -8377,7 +8740,7 @@ var ts; ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -8389,7 +8752,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -8694,10 +9057,10 @@ var ts; function isExportDefaultSymbol(symbol) { return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); } - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -8818,6 +9181,26 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -8899,6 +9282,8 @@ var ts; } ts.formatObjectFlags = formatObjectFlags; function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -9030,6 +9415,8 @@ var ts; if (!parent) return 0; switch (parent.kind) { + case 193: + return accessKind(parent); case 201: case 200: var operator = parent.operator; @@ -9041,11 +9428,31 @@ var ts; : 0; case 187: return parent.name !== node ? 0 : accessKind(parent); + case 273: { + var parentAccess = accessKind(parent.parent); + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274: + return node === parent.objectAssignmentInitializer ? 0 : accessKind(parent.parent); + case 185: + return accessKind(parent); default: return 0; } function writeOrReadWrite() { - return parent.parent && parent.parent.kind === 219 ? 1 : 2; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 ? 1 : 2; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0: + return 1; + case 1: + return 0; + case 2: + return 2; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -9254,12 +9661,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -9469,7 +9870,7 @@ var ts; if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219: var expr = hostNode.expression; switch (expr.kind) { @@ -9481,9 +9882,7 @@ var ts; return arg; } } - return undefined; - case 1: - return undefined; + break; case 193: { return getDeclarationIdentifier(hostNode.expression); } @@ -9491,10 +9890,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -9523,7 +9920,7 @@ var ts; } case 202: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1: case 4: case 5: @@ -9584,6 +9981,13 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; function hasJSDocParameterTags(node) { return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } @@ -9671,7 +10075,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -10917,7 +11334,7 @@ var ts; } function isDeclaration(node) { if (node.kind === 148) { - return node.parent.kind !== 301 || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -11269,6 +11686,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -11285,9 +11714,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -11299,13 +11727,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -11498,8 +11927,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -11694,6 +12121,13 @@ var ts; } ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42, 63]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -11925,30 +12359,35 @@ var ts; } } ts.getScriptKindFromFileName = getScriptKindFromFileName; - ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; - ts.supportedJavascriptExtensions = [".js", ".jsx"]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTSExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; + ts.supportedJSExtensions = [".js", ".jsx"]; + ts.supportedJSAndJsonExtensions = [".js", ".jsx", ".json"]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function isJSLike(scriptKind) { return scriptKind === 1 || scriptKind === 2; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; @@ -12057,14 +12496,14 @@ var ts; return !(pos >= 0); } ts.positionIsSynthesized = positionIsSynthesized; - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json"; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json"; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); @@ -12219,6 +12658,10 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; })(ts || (ts = {})); var ts; (function (ts) { @@ -12282,6 +12725,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275: @@ -12352,6 +12796,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -12710,7 +13155,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, 6); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); @@ -12776,8 +13221,12 @@ var ts; if (scriptKind === 6) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -13940,8 +14389,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288, dotdotdot.pos); variadic.type = type; @@ -15554,6 +16005,7 @@ var ts; var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); node.questionToken = parseOptionalToken(55); + node.exclamationToken = parseOptionalToken(51); if (asteriskToken || token() === 19 || token() === 27) { return parseMethodDeclaration(node, asteriskToken); } @@ -16916,7 +17368,7 @@ var ts; nextJSDocToken(); } } - function skipWhitespaceOrAsterisk() { + function skipWhitespaceOrAsterisk(next) { if (token() === 5 || token() === 4) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; @@ -16930,7 +17382,7 @@ var ts; else if (token() === 39) { precedingLineBreak = false; } - nextJSDocToken(); + next(); } } function parseTag(indent) { @@ -16938,8 +17390,8 @@ var ts; var atToken = createNode(57, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespaceOrAsterisk(); + var tagName = parseJSDocIdentifierName(undefined, nextToken); + skipWhitespaceOrAsterisk(nextToken); var tag; switch (tagName.escapedText) { case "augments": @@ -17069,7 +17521,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); return token() === 17 ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -17100,7 +17552,7 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { @@ -17109,10 +17561,8 @@ var ts; var result = target === 1 ? createNode(303, atToken.pos) : createNode(297, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -17126,14 +17576,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 || child.kind === 303) { children = ts.append(children, child); } @@ -17221,7 +17671,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(nextJSDocToken); var typedefTag = createNode(302, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -17236,7 +17686,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290, start_3); } @@ -17296,7 +17746,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -17336,17 +17786,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 || child.kind === 303) && target !== 4 && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -17374,7 +17824,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57); var atToken = createNode(57); atToken.end = scanner.getTextPos(); @@ -17400,9 +17850,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { var constraint; @@ -17451,7 +17899,8 @@ var ts; } return entity; } - function parseJSDocIdentifierName(message) { + function parseJSDocIdentifierName(message, next) { + if (next === void 0) { next = nextJSDocToken; } if (!ts.tokenIsIdentifierOrKeyword(token())) { return createMissingNode(71, !message, message || ts.Diagnostics.Identifier_expected); } @@ -17460,7 +17909,7 @@ var ts; var result = createNode(71, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); - nextJSDocToken(); + next(); return result; } } @@ -18014,7 +18463,7 @@ var ts; ]; ts.libs = libEntries.map(function (entry) { return entry[0]; }); ts.libMap = ts.createMapFromEntries(libEntries); - ts.optionDeclarations = [ + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -18028,6 +18477,41 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -18075,21 +18559,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, { name: "target", shortName: "t", @@ -18103,6 +18572,8 @@ var ts; es2018: 5, esnext: 6, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18121,6 +18592,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18133,6 +18605,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -18140,6 +18613,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -18157,6 +18631,7 @@ var ts; "react-native": 3, "react": 2 }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18265,6 +18740,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18273,6 +18749,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18281,6 +18758,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18289,6 +18767,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18297,6 +18776,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18305,6 +18785,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18337,6 +18818,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -18348,6 +18830,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -18355,6 +18838,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -18362,6 +18846,7 @@ var ts; { name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -18375,6 +18860,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -18386,6 +18872,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -18396,6 +18883,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -18477,30 +18965,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -18558,12 +19028,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -18576,6 +19048,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -18621,6 +19094,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -18628,6 +19102,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -18681,7 +19156,41 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", @@ -18727,20 +19236,20 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } @@ -18773,16 +19282,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -18794,14 +19302,14 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } else { if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -18834,7 +19342,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -18877,8 +19385,18 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -18890,7 +19408,32 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + projects.push("."); + } + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -19414,7 +19957,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -19431,8 +19975,21 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + if (filesSpecs.length === 0 && hasZeroOrNoReferences) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -19473,14 +20030,13 @@ var ts; } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -19488,7 +20044,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -19588,11 +20143,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -19638,7 +20188,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -19646,7 +20196,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -19792,7 +20342,7 @@ var ts; validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { @@ -19825,12 +20375,8 @@ var ts; } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -19981,6 +20527,12 @@ var ts; function noPackageId(r) { return withPackageId(undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; @@ -19992,7 +20544,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -20001,45 +20553,92 @@ var ts; failedLookupLocations: failedLookupLocations }; } - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); } - return; } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); } - return path; + return; } - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); } - return result.config; + return; } - catch (e) { - return {}; + return result; + } + var typeScriptVersion; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -20073,7 +20672,8 @@ var ts; var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -20093,7 +20693,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -20119,11 +20718,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -20138,7 +20737,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); + var result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, undefined); var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -20167,8 +20766,8 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { result.push(ts.getBaseFileName(normalized)); } @@ -20312,15 +20911,15 @@ var ts; return result; } ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -20354,7 +20953,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -20371,7 +20970,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -20382,66 +20981,53 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -20453,8 +21039,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -20462,7 +21048,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -20475,7 +21061,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, false, state, true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } @@ -20491,29 +21077,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -20521,7 +21108,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } ts.nodeModulesPathPart = "/node_modules/"; function parseNodeModuleFromPath(resolved) { @@ -20550,41 +21137,37 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json"); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -20598,11 +21181,11 @@ var ts; return tryExtension(".json"); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -20616,40 +21199,41 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); - } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state); if (fromPackageJson) { return fromPackageJson; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(candidate, state.host); + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { - var path = tryReadPackageJsonFields(true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts"; } @@ -20661,6 +21245,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts")) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -20672,21 +21257,22 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); + function loadModuleFromPackageJson(jsonContent, versionPaths, extensions, candidate, state) { + var file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) + : readPackageJsonMainField(jsonContent, candidate, state); if (!file) { if (extensions === Extensions.TypeScript) { - file = tryReadPackageJsonFields(false, jsonContent, candidate, state); + file = readPackageJsonMainField(jsonContent, candidate, state); if (!file) { return undefined; } @@ -20695,23 +21281,32 @@ var ts; return undefined; } } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, false); + }; + var onlyRecordFailures = !ts.directoryProbablyExists(ts.getDirectoryPath(file), state.host); + if (versionPaths && ts.containsPath(candidate, file)) { + var moduleName = ts.getRelativePathFromDirectory(candidate, file, false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); - if (result) { - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state)); } function resolvedIfExtensionMatches(extensions, path) { var ext = ts.tryGetExtensionFromPath(path); @@ -20729,90 +21324,132 @@ var ts; return extension === ".d.ts"; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, true, undefined); + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, true, undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } return mangled; } function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -20821,63 +21458,64 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; - function getPackageNameFromAtTypesDirectory(mangledName) { + ts.mangleScopedPackageName = mangleScopedPackageName; + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; - function getUnmangledNameForScopedPackage(typesPackageName) { + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, false, state)); } } } @@ -20887,9 +21525,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, false); return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -21046,12 +21684,16 @@ var ts; if (symbolFlags & (32 | 64 | 2048 | 4096) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + symbol.valueDeclaration = node; } } function getDeclarationName(node) { @@ -21091,7 +21733,7 @@ var ts; case 277: return "export="; case 202: - if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + if (ts.getAssignmentDeclarationKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); @@ -21133,7 +21775,7 @@ var ts; if (symbol.isReplaceableByMethod) { symbolTable.set(name, symbol = createSymbol(0, name)); } - else { + else if (!(includes & 3 && symbol.flags & 67108864)) { if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -21188,12 +21830,12 @@ var ts; } else { if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } - var exportKind = symbolFlags & 67216319 ? 1048576 : 0; + var exportKind = symbolFlags & 67220415 ? 1048576 : 0; var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -21425,6 +22067,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200: return expr.operator === 51 && isNarrowingExpression(expr.operand); + case 197: + return isNarrowingExpression(expr.expression); } return false; } @@ -22147,7 +22791,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 67215503); + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 110735); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -22164,7 +22808,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 67215503 : 0); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 110735 : 0); return state; } function bindFunctionOrConstructorType(node) { @@ -22232,9 +22876,6 @@ var ts; declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 67216319); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -22254,7 +22895,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288, 67901928); + bindBlockScopedDeclaration(typeAlias, 524288, 67897832); } else { bind(typeAlias.fullName); @@ -22426,7 +23067,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -22466,7 +23107,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288, 67901928); + bindBlockScopedDeclaration(parentNode, 524288, 67897832); break; } case 99: @@ -22482,15 +23123,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, undefined, node.expression, 1 | 134217728, 67216318); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, undefined, node.expression, 1 | 134217728, 67220414); } break; case 202: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1: bindExportsPropertyAssignment(node); @@ -22558,15 +23199,15 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 154: case 153: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67208127); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67212223); case 237: return bindFunctionDeclaration(node); case 155: return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 156: - return bindPropertyOrMethodOrAccessor(node, 32768, 67150783); + return bindPropertyOrMethodOrAccessor(node, 32768, 67154879); case 157: - return bindPropertyOrMethodOrAccessor(node, 65536, 67183551); + return bindPropertyOrMethodOrAccessor(node, 65536, 67187647); case 163: case 287: case 291: @@ -22582,7 +23223,7 @@ var ts; case 195: return bindFunctionExpression(node); case 189: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -22591,9 +23232,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239: - return bindBlockScopedDeclaration(node, 64, 67901832); + return bindBlockScopedDeclaration(node, 64, 67897736); case 240: - return bindBlockScopedDeclaration(node, 524288, 67901928); + return bindBlockScopedDeclaration(node, 524288, 67897832); case 241: return bindEnumDeclaration(node); case 242: @@ -22668,10 +23309,13 @@ var ts; bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); } else { - var flags = node.kind === 252 && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) ? 2097152 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + if (node.isExportEquals) { + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { @@ -22751,7 +23395,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, false); switch (thisContainer.kind) { case 237: @@ -22800,7 +23444,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, false); + bindPropertyAssignment(lhs.expression, lhs, false); } function bindPrototypePropertyAssignment(lhs, parent) { var classPrototype = lhs.expression; @@ -22813,7 +23457,7 @@ var ts; function bindSpecialPropertyAssignment(node) { var lhs = node.left; var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } node.left.parent = node; @@ -22831,36 +23475,36 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 : propertyAccess.parent.parent.kind === 277; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920))) { var flags_1 = 1536 | 67108864; - var excludeFlags_1 = 67215503 & ~67108864; + var excludeFlags_1 = 110735 & ~67108864; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 : 4) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 : 0) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 : 4; + var excludes = isMethod ? 67212223 : 0; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864, excludes & ~67108864); } - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 | 32 | 1024)) { return true; } @@ -22873,7 +23517,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 ? init.right : init, isPrototypeAssignment); } return false; } @@ -22945,14 +23589,17 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 : 0); + var enumExcludes = (isEnum ? 68008191 : 0); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 | enumFlags, 67220415 | enumExcludes); } else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 67216319); + declareSymbolAndAddToSymbolTable(node, 1, 67220415); } else { - declareSymbolAndAddToSymbolTable(node, 1, 67216318); + declareSymbolAndAddToSymbolTable(node, 1 | enumFlags, 67220414 | enumExcludes); } } } @@ -22967,7 +23614,7 @@ var ts; bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1, 67216319); + declareSymbolAndAddToSymbolTable(node, 1, 67220415); } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; @@ -22983,10 +23630,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 67215791); + bindBlockScopedDeclaration(node, 16, 67219887); } else { - declareSymbolAndAddToSymbolTable(node, 16, 67215791); + declareSymbolAndAddToSymbolTable(node, 16, 67219887); } } function bindFunctionExpression(node) { @@ -23024,10 +23671,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, undefined, node, 262144, 67639784); + declareSymbol(container_1.locals, undefined, node, 262144, 67635688); } else { - declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); } } else if (node.parent.kind === 174) { @@ -23036,14 +23683,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, undefined, node, 262144, 67639784); + declareSymbol(container_2.locals, undefined, node, 262144, 67635688); } else { bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); } } function shouldReportErrorOnModuleDeclaration(node) { @@ -23057,8 +23704,7 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 218) || node.kind === 238 || - (node.kind === 242 && shouldReportErrorOnModuleDeclaration(node)) || - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -23085,7 +23731,7 @@ var ts; } } function isExecutableStatement(s) { - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 | 2)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { @@ -23121,6 +23767,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } function computeTransformFlagsForNode(node, subtreeFlags) { @@ -24013,6 +24662,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); var cancellationToken; var requestedExternalEmitHelpers; var externalHelpersModule; @@ -24022,7 +24683,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -24230,8 +24892,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -24295,7 +24957,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -24325,8 +24988,19 @@ var ts; var stringType = createIntrinsicType(4, "string"); var numberType = createIntrinsicType(8, "number"); var falseType = createIntrinsicType(256, "false"); + var regularFalseType = createIntrinsicType(256, "false"); var trueType = createIntrinsicType(256, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256, "true"); + falseType.flags |= 33554432; + trueType.flags |= 33554432; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024, "symbol"); var voidType = createIntrinsicType(4096, "void"); var neverType = createIntrinsicType(32768, "never"); @@ -24546,35 +25220,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2) - result |= 67216319; + result |= 67220415; if (flags & 1) - result |= 67216318; + result |= 67220414; if (flags & 4) result |= 0; if (flags & 8) result |= 68008959; if (flags & 16) - result |= 67215791; + result |= 67219887; if (flags & 32) result |= 68008383; if (flags & 64) - result |= 67901832; + result |= 67897736; if (flags & 256) result |= 68008191; if (flags & 128) result |= 68008831; if (flags & 512) - result |= 67215503; + result |= 110735; if (flags & 8192) - result |= 67208127; + result |= 67212223; if (flags & 32768) - result |= 67150783; + result |= 67154879; if (flags & 65536) - result |= 67183551; + result |= 67187647; if (flags & 262144) - result |= 67639784; + result |= 67635688; if (flags & 524288) - result |= 67901928; + result |= 67897832; if (flags & 2097152) result |= 2097152; return result; @@ -24614,6 +25288,7 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { target.valueDeclaration = source.valueDeclaration; } @@ -24652,12 +25327,12 @@ var ts; var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); @@ -24674,7 +25349,7 @@ var ts; } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); }); } @@ -24772,8 +25447,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -24880,14 +25555,14 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 67901928 && lastLocation.kind !== 289) { + if (meaning & result.flags & 67897832 && lastLocation.kind !== 289) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 149 || lastLocation.kind === 148 : false; } - if (meaning & 67216319 && result.flags & 1) { + if (meaning & 67220415 && result.flags & 1) { useResult = lastLocation.kind === 149 || (lastLocation === location.type && @@ -24946,7 +25621,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319)) { + if (lookup(ctor.locals, name, meaning & 67220415)) { propertyWithInvalidInitializer = location; } } @@ -24955,7 +25630,7 @@ var ts; case 238: case 207: case 239: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928)) { + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -24977,7 +25652,7 @@ var ts; case 209: if (lastLocation === location.expression && location.parent.token === 85) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -24988,7 +25663,7 @@ var ts; case 147: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239) { - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -25053,7 +25728,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, false)) { return requireSymbol; } @@ -25094,13 +25769,13 @@ var ts; } if (errorLocation && (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 67216319) === 67216319))) { + ((meaning & 32 || meaning & 384) && (meaning & 67220415) === 67220415))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 67216319) === 67216319 && !(originalLocation.flags & 2097152)) { + if (result && isInExternalModule && (meaning & 67220415) === 67220415 && !(originalLocation.flags & 2097152)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); @@ -25188,9 +25863,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(errorLocation) ? 67216319 : 0); + var namespaceMeaning = 1920 | (ts.isInJSFile(errorLocation) ? 67220415 : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~namespaceMeaning, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~namespaceMeaning, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -25209,29 +25884,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 & ~1024)) { + if (meaning & (67220415 & ~1024)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~67216319, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~67220415, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 & ~1024 & ~67901928)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67216319, undefined, undefined, false)); + if (meaning & (67220415 & ~1024 & ~67897832)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67220415, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 & ~1024 & ~67216319)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67901928, undefined, undefined, false)); + else if (meaning & (67897832 & ~1024 & ~67220415)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67897832, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -25258,6 +25936,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -25313,7 +25994,7 @@ var ts; } return true; } - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); @@ -25347,7 +26028,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 | 1920)) { + if (valueSymbol.flags & (67897832 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -25434,7 +26115,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 | 67901928 | 1920, true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 | 67897832 | 1920, true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -25453,7 +26134,7 @@ var ts; case 251: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255: - return getTargetOfExportSpecifier(node, 67216319 | 67901928 | 1920, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 | 67897832 | 1920, dontRecursivelyResolve); case 252: case 202: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -25464,7 +26145,7 @@ var ts; } } function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 | 67901928 | 1920; } + if (excludes === void 0) { excludes = 67220415 | 67897832 | 1920; } if (!symbol) return false; return (symbol.flags & (2097152 | excludes)) === 2097152 || !!(symbol.flags & 2097152 && symbol.flags & 67108864); @@ -25498,7 +26179,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -25531,7 +26212,7 @@ var ts; } else { ts.Debug.assert(entityName.parent.kind === 246); - return resolveEntityName(entityName, 67216319 | 67901928 | 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 | 67897832 | 1920, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -25541,11 +26222,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(name) ? meaning & 67216319 : 0); + var namespaceMeaning = 1920 | (ts.isInJSFile(name) ? meaning & 67220415 : 0); var symbol; if (name.kind === 71) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); if (!symbol) { return symbolFromJSPrototype; @@ -25561,7 +26242,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -25590,15 +26271,15 @@ var ts; ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -25606,9 +26287,19 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3) { + ts.getAssignmentDeclarationKind(host.expression) === 3) { var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6) { + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -25616,6 +26307,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -25645,7 +26343,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(false, errorNode, resolvedModule, moduleReference); } return getMergedSymbol(sourceFile.symbol); @@ -25661,7 +26359,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -25691,7 +26389,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -25699,7 +26397,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json") && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -25711,17 +26409,15 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages(undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages(undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias), moduleSymbol)) || moduleSymbol; @@ -25937,7 +26633,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67216319); + return !!(symbol.flags & 67220415 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67220415); } function findConstructorDeclaration(node) { var members = node.members; @@ -26030,7 +26726,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 67216319 ? 67216319 : 1920; + return rightMeaning === 67220415 ? 67220415 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -26069,7 +26765,8 @@ var ts; && symbolFromSymbolTable.escapedName !== "export=" && symbolFromSymbolTable.escapedName !== "default" && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -26126,11 +26823,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832, false); return access.accessibility === 0; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415, false); return access.accessibility === 0; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -26154,7 +26851,14 @@ var ts; }; } } - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -26242,14 +26946,14 @@ var ts; if (entityName.parent.kind === 165 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147) { - meaning = 67216319 | 1048576; + meaning = 67220415 | 1048576; } else if (entityName.kind === 146 || entityName.kind === 187 || entityName.parent.kind === 246) { meaning = 1920; } else { - meaning = 67901928; + meaning = 67897832; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); @@ -26398,13 +27102,13 @@ var ts; } if (type.flags & 512 && !(type.flags & 262144)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928, false); + var parentName = symbolToName(parentSymbol, context, 67897832, false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 544) { - var name = symbolToName(type.symbol, context, 67901928, false); + var name = symbolToName(type.symbol, context, 67897832, false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, undefined); } @@ -26424,7 +27128,7 @@ var ts; if (!(context.flags & 1048576)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319); + return symbolToTypeNode(type.symbol, context, 67220415); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -26490,14 +27194,14 @@ var ts; return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 | 8), undefined); } return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928) + ? symbolToTypeNode(type.symbol, context, 67897832) : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832, typeArgumentNodes); } if (type.flags & (262144 | 524288)) { var types = type.flags & 262144 ? formatUnionTypes(type.types) : type.types; @@ -26567,19 +27271,19 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 : 67216319; + if (isJSConstructor(symbol.valueDeclaration)) { + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 : 67220415; return symbolToTypeNode(symbol, context, isInstanceType); } else if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319); + return symbolToTypeNode(symbol, context, 67220415); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - return symbolToTypeNode(typeAlias, context, 67901928); + return symbolToTypeNode(typeAlias, context, 67897832); } else { context.approximateLength += 3; @@ -26657,8 +27361,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -26694,7 +27398,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16; - var ref = symbolToTypeNode(parent, context, 67901928, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -26707,7 +27411,7 @@ var ts; } var flags = context.flags; context.flags |= 16; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -26801,17 +27505,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 | 1048576, undefined, undefined, true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319, true); + var propertyName = symbolToName(propertySymbol, context, 67220415, true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; @@ -26930,7 +27630,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928, undefined, type.symbol.escapedName, false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832, undefined, type.symbol.escapedName, false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -26941,7 +27641,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8) - : symbolToName(type.symbol, context, 67901928, true); + : symbolToName(type.symbol, context, 67897832, true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -26980,6 +27680,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184) { @@ -26989,6 +27692,15 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 | 1048576, undefined, undefined, true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; @@ -27089,7 +27801,10 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -27097,7 +27812,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); - var isTypeOf = meaning === 67216319; + var isTypeOf = meaning === 67220415; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); @@ -27252,7 +27967,7 @@ var ts; var baseType = t.flags & 256 ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -27411,10 +28126,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252) { - exportSymbol = resolveName(node, node.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, node, false); + exportSymbol = resolveName(node, node.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, node, false); } else if (node.parent.kind === 255) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 | 67901928 | 1920 | 2097152); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 | 67897832 | 1920 | 2097152); } var result; if (exportSymbol) { @@ -27434,7 +28149,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 | 67901928 | 1920, undefined, undefined, false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 | 67897832 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -27471,6 +28186,8 @@ var ts; switch (propertyName) { case 0: return !!getSymbolLinks(target).type; + case 5: + return !!(getNodeLinks(target).resolvedEnumType); case 2: return !!getSymbolLinks(target).declaredType; case 1: @@ -27688,7 +28405,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1) && !(declaration.flags & 4194304)) { if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { @@ -27712,15 +28429,21 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } var type = declaration.symbol.escapedName === "this" ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } if (declaration.initializer) { @@ -27735,15 +28458,15 @@ var ts; } return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -27757,8 +28480,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -27766,16 +28489,16 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; if (!type) { var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -27793,8 +28516,8 @@ var ts; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -27813,7 +28536,7 @@ var ts; type.objectFlags |= 16384; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -27826,10 +28549,10 @@ var ts; } return declaredType; } - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 && - special === 2 && + kind === 2 && symbol.escapedName === "export=") { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -27875,8 +28598,8 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, false).parent; return ts.isClassLike(parent) && parent; }); @@ -27884,7 +28607,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -28007,7 +28730,14 @@ var ts; } if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252) { return checkExpression(declaration.expression); @@ -28016,9 +28746,9 @@ var ts; return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -28031,7 +28761,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -28092,7 +28822,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156); var setter = ts.getDeclarationOfKind(symbol, 157); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -28146,7 +28876,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -28173,7 +28903,7 @@ var ts; } else if (declaration.kind === 202 || declaration.kind === 187 && declaration.parent.kind === 202) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -28182,11 +28912,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=")); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16, symbol); @@ -28206,7 +28936,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 67216319 + links.type = targetSymbol.flags & 67220415 ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -28215,22 +28945,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -28375,15 +29097,15 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { + var isJavascript = ts.isInJSFile(location); + if (isJSConstructorType(type) && !typeArgCount) { return getSignaturesOfType(type, 0); } return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); @@ -28391,7 +29113,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -28460,8 +29182,8 @@ var ts; else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJSClassType(baseConstructorType.symbol) || anyType; } else { var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); @@ -28542,7 +29264,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928, true); + var baseSymbol = resolveEntityName(node.expression, 67897832, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -28671,9 +29393,9 @@ var ts; if (declaration.kind === 241) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -28851,7 +29573,7 @@ var ts; if (type.flags & 2048) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192) { + if (type.flags & (64 | 128)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -28866,7 +29588,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319) { + if (symbolFlags & 67220415) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -29067,7 +29789,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -29505,10 +30227,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -29520,7 +30247,8 @@ var ts; } function getConstraintOfDistributiveConditionalType(type) { if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -29582,6 +30310,7 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -29589,8 +30318,14 @@ var ts; if (!pushTypeResolution(t, 4)) { return circularConstraintType; } + if (constraintDepth === 50) { + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -29612,8 +30347,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -29628,7 +30363,7 @@ var ts; if (t.flags & 2097152) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304) { @@ -29638,9 +30373,6 @@ var ts; if (t.flags & 8388608) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -29677,16 +30409,31 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } function getApparentType(type) { var t = type.flags & 15794176 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 ? globalStringType : - t.flags & 168 ? globalNumberType : - t.flags & 272 ? globalBooleanType : - t.flags & 3072 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : - t.flags & 1048576 ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 ? getApparentTypeOfMappedType(t) : + t.flags & 524288 ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 ? globalStringType : + t.flags & 168 ? globalNumberType : + t.flags & 272 ? globalBooleanType : + t.flags & 3072 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 16777216 ? emptyObjectType : + t.flags & 1048576 ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -29867,7 +30614,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 286 + return ts.isInJSFile(node) && (node.type && node.type.kind === 286 || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; return isBracketed || !!typeExpression && typeExpression.type.kind === 286; @@ -29957,7 +30704,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -29966,7 +30713,7 @@ var ts; var paramSymbol = param.symbol; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319, undefined, undefined, false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -30001,7 +30748,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; @@ -30024,7 +30771,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -30108,7 +30855,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -30185,7 +30932,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -30204,8 +30951,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -30239,7 +30990,7 @@ var ts; signature; } function createCanonicalSignature(signature) { - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -30409,7 +31160,7 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { var missingAugmentsTag = isJs && node.parent.kind !== 293; @@ -30438,7 +31189,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -30485,20 +31236,33 @@ var ts; if (type) { return type; } + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); if (jsdocType) { return jsdocType; } - resolveTypeReferenceName(getTypeReferenceName(node), 67901928); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832); return getTypeOfSymbol(symbol); } function getJSDocTypeReference(node, symbol, typeArguments) { @@ -30508,10 +31272,6 @@ var ts; if (referenceType || assignedType) { return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); - } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 | 64)) { @@ -30626,10 +31386,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928; + var meaning = 67897832; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319; + meaning |= 67220415; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -30678,10 +31438,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name, false); @@ -30734,7 +31494,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928, undefined); + var symbol = getGlobalSymbol(name, 67897832, undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -30901,10 +31661,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -30917,15 +31674,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -30971,7 +31719,7 @@ var ts; var remove = t.flags & 64 && includes & 4 || t.flags & 128 && includes & 8 || t.flags & 2048 && includes & 1024 || - t.flags & 192 && t.flags & 33554432 && containsType(types, t.regularType); + t.flags & 448 && t.flags & 33554432 && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -30992,7 +31740,7 @@ var ts; } switch (unionReduction) { case 1: - if (includes & 2240) { + if (includes & 2240 | 256) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -31080,18 +31828,15 @@ var ts; if (type === wildcardType) includes |= 268435456; } - else if ((strictNullChecks || !(flags & 24576)) && !ts.contains(typeSet, type) && - !(flags & 131072 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } return includes; } function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -31308,7 +32053,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? @@ -31321,7 +32066,7 @@ var ts; markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 99); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; @@ -31380,7 +32125,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -31398,7 +32143,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 | 134217728); @@ -31406,18 +32154,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 | 1048576); } - function isStringIndexOnlyType(type) { - if (type.flags & 131072 && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 ? getSimplifiedIndexedAccessType(type) : type; } @@ -31427,27 +32163,16 @@ var ts; } type.simplified = circularConstraintType; var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 && isGenericObjectType(objectType)) { - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + if (indexType.flags & 262144) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + if (!(indexType.flags & 15794176)) { + if (objectType.flags & 262144) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + if (objectType.flags & 524288) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } if (isGenericMappedType(objectType)) { @@ -31466,7 +32191,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -31484,17 +32210,26 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 && !(indexType.flags & 16)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false, missingType); + if (propType === missingType) { + if (!accessNode) { + return missingType; + } + else { + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -31653,7 +32388,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 : node.flags & 2097152 ? 67216319 | 67901928 : 67901928; + var targetMeaning = node.isTypeOf ? 67220415 : node.flags & 2097152 ? 67220415 | 67897832 : 67897832; var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; @@ -31682,7 +32417,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 + var errorMessage = targetMeaning === 67220415 ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -31696,7 +32431,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319) { + if (meaning === 67220415) { return links.resolvedType = getTypeOfSymbol(symbol); } else { @@ -31830,7 +32565,7 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 && !(type.flags & 33554432)) { + if (type.flags & 448 && !(type.flags & 33554432)) { if (!type.freshType) { var freshType = createLiteralType(type.flags | 33554432, type.value, type.symbol); freshType.regularType = type; @@ -31841,7 +32576,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 && type.flags & 33554432 ? type.regularType : + return type.flags & 448 && type.flags & 33554432 ? type.regularType : type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -32037,7 +32772,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -32119,7 +32854,7 @@ var ts; var typeParameters = links.outerTypeParameters; if (!typeParameters) { var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -32129,7 +32864,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -32182,30 +32917,34 @@ var ts; return !!ts.forEachChild(node, containsReference); } } - function instantiateMappedType(type, mapper) { + function getHomomorphicTypeVariable(type) { var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 1048576) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); - } + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536) { + return typeVariable; } } - return instantiateAnonymousType(type, mapper); + return undefined; } - function isMappableType(type) { - return type.flags & (3 | 14745600 | 131072 | 524288); + function instantiateMappedType(type, mapper) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 | 14745600 | 131072 | 524288) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + } + } + return instantiateAnonymousType(type, mapper); } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; @@ -32263,46 +33002,59 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536) { - return mapper(type); - } - if (type.flags & 131072) { - if (type.objectFlags & 16) { - return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } - } - if (type.flags & 262144 && !(type.flags & 32764)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536) { + return mapper(type); + } + if (flags & 131072) { + var objectFlags = type.objectFlags; + if (objectFlags & 16) { + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 4194304) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + if (objectFlags & 32) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 8388608) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 && !(flags & 32764)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -32367,7 +33119,7 @@ var ts; return body.kind === 216 ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -32419,53 +33171,116 @@ var ts; return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); } function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 || (type.flags & 524288 && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268: case 193: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202: switch (node.operatorToken.kind) { case 58: case 26: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0); + var constructSignatures = getSignaturesOfType(source, 1); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 | 32768)) && checkTypeRelatedTo(returnType, target, relation, undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + if (ts.isBlock(node.body)) { + return false; + } + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, undefined, undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, undefined); if (elaborated) { reportedError = true; } else { var resultObj = {}; var specificSource = next ? checkExpressionForMutableLocation(next, 0, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, undefined, resultObj); if (result && specificSource !== sourcePropType) { - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -32476,13 +33291,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168) && getIndexInfoOfType(target, 1) || getIndexInfoOfType(target, 0) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -32516,8 +33334,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -32548,9 +33366,13 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + var tupleizedType = checkArrayLiteral(node, 3, true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -32599,8 +33421,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); @@ -32621,9 +33443,9 @@ var ts; source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { return 0; } var kind = target.declaration ? target.declaration.kind : 0; @@ -32645,11 +33467,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && @@ -32666,13 +33488,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); @@ -32828,10 +33650,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 && source.flags & 33554432) { + if (source.flags & 448 && source.flags & 33554432) { source = source.regularType; } - if (target.flags & 192 && target.flags & 33554432) { + if (target.flags & 448 && target.flags & 33554432) { target = target.regularType; } if (source === target || @@ -32946,10 +33768,10 @@ var ts; } function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 && source.flags & 33554432) { + if (source.flags & 448 && source.flags & 33554432) { source = source.regularType; } - if (target.flags & 192 && target.flags & 33554432) { + if (target.flags & 448 && target.flags & 33554432) { target = target.regularType; } if (source.flags & 8388608) { @@ -32991,13 +33813,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432) && - !(target.flags & 262144) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 | 131072 | 524288) && source !== globalObjectType && + target.flags & (131072 | 524288) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0); @@ -33070,7 +33889,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072) { + if (flags & 131072 || flags & 2097152 || flags & 4194304 || flags & 1048576 || flags & 8388608) { return recursiveTypeRelatedTo(source, target, false); } if (flags & (262144 | 524288)) { @@ -33080,32 +33899,6 @@ var ts; } } } - if (flags & 1048576) { - return isRelatedTo(source.type, target.type, false); - } - if (flags & 2097152) { - if (result = isRelatedTo(source.objectType, target.objectType, false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, false)) { - return result; - } - } - } - if (flags & 4194304) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608) { - return isRelatedTo(source.substitute, target.substitute, false); - } return 0; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -33122,7 +33915,7 @@ var ts; return hasExcessProperties(source, discriminant, undefined, reportErrors); } var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { if (!errorNode) return { value: ts.Debug.fail() }; @@ -33161,6 +33954,9 @@ var ts; } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; @@ -33189,7 +33985,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], true); } return 0; @@ -33216,6 +34013,14 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } function findMatchingDiscriminantType(source, target) { var match; var sourceProperties = getPropertiesOfObjectType(source); @@ -33383,6 +34188,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072)) { + if (flags & 1048576) { + return isRelatedTo(source.type, target.type, false); + } + var result_2 = 0; + if (flags & 2097152) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_2; + } + } + } + if (flags & 4194304) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608) { + return isRelatedTo(source.substitute, target.substitute, false); + } + return 0; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -33407,18 +34243,19 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1) { + return -1; } } } } else if (target.flags & 2097152) { - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + if (relation !== identityRelation) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -33434,7 +34271,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -33502,6 +34338,25 @@ var ts; } } else { + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0; + } + var sourceIsPrimitive = !!(source.flags & 32764); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && !(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) { var variances = getVariances(source.target); @@ -33516,29 +34371,20 @@ var ts; errorInfo = saveErrorInfo; } } - var sourceIsPrimitive = !!(source.flags & 32764); - if (relation !== identityRelation) { - source = getApparentType(source); + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1) || anyType, getIndexTypeOfType(target, 1) || anyType, reportErrors); } if (source.flags & (131072 | 524288) && target.flags & 131072) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); } } } @@ -33558,10 +34404,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -33684,29 +34530,6 @@ var ts; } return result; } - function isWeakType(type) { - if (type.flags & 131072) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); - } - if (type.flags & 524288) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 && target.flags & 131072)) { return 0; @@ -33738,8 +34561,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1) ? 0 : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1) ? @@ -33907,6 +34730,29 @@ var ts; return false; } } + function isWeakType(type) { + if (type.flags & 131072) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + } + if (type.flags & 524288) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); result.objectFlags |= 8192; @@ -34134,8 +34980,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34205,10 +35051,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 && type.flags & 33554432 ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 && type.flags & 33554432 ? stringType : type.flags & 128 && type.flags & 33554432 ? numberType : - type.flags & 256 ? booleanType : + type.flags & 256 && type.flags & 33554432 ? booleanType : type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -34229,13 +35075,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -34244,7 +35094,7 @@ var ts; return type.flags & 262144 ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 ? type.value === "" ? 64 : 0 : type.flags & 128 ? type.value === 0 ? 128 : 0 : - type.flags & 256 ? type === falseType ? 256 : 0 : + type.flags & 256 ? (type === falseType || type === regularFalseType) ? 256 : 0 : type.flags & 29148; } function removeDefinitelyFalsyTypes(type) { @@ -34258,11 +35108,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 ? emptyStringType : type.flags & 8 ? zeroType : - type.flags & 16 || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 | 8192 | 16384) || - type.flags & 64 && type.value === "" || - type.flags & 128 && type.value === 0 ? type : - neverType; + type.flags & 64 && type.value === "" || + type.flags & 128 && type.value === 0 ? type : + neverType; } function getNullableType(type, flags) { var missing = (flags & ~type.flags) & (8192 | 16384); @@ -34516,19 +35367,23 @@ var ts; function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) : + sourceRestType ? targetCount : + Math.min(sourceCount, targetCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -34801,6 +35656,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432) { var targetTypes = target.types; var typeVariableCount = 0; @@ -34831,7 +35689,11 @@ var ts; } else { if (!(priority & 32 && source.flags & (524288 | 15794176))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + if (apparentSource !== source && !(apparentSource.flags & (131072 | 524288))) { + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 | 524288)) { var key = source.id + "," + target.id; @@ -34914,33 +35776,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); - } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -34950,12 +35817,15 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -34986,8 +35856,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35006,7 +35876,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 | 1048576); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 | 1048576); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128); @@ -35024,7 +35894,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { var candidates = widenObjectLiteralCandidates(inference.candidates); var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); var widenLiteralTypes = !primitiveConstraint && inference.topLevel && @@ -35032,7 +35902,7 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = context.flags & 1 || inference.priority & 28 ? + var unwidenedType = inference.priority & 28 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -35043,14 +35913,14 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { - if (inference.contraCandidates) { - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & 32768)) { + inference.candidates = [getContravariantInference(inference)]; inference.contraCandidates = undefined; } if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + inferredType = getCovariantInference(inference, signature); } - else if (context.flags & 2) { + else if (context.flags & 1) { inferredType = silentNeverType; } else { @@ -35059,7 +35929,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2)); } } } @@ -35087,11 +35957,40 @@ var ts; } return result; } + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 67220415 | 1048576, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35250,13 +36149,28 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { if (assignedType.flags & 32768) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 && assignedType.flags & 256) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); + } + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -35264,8 +36178,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -35300,13 +36214,15 @@ var ts; } if (flags & 272) { return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; + (type === falseType || type === regularFalseType) ? 3030404 : 1981828 : + (type === falseType || type === regularFalseType) ? 3145092 : 4193668; } if (flags & 131072) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 : 4181984 : - strictNullChecks ? 1972176 : 4184016; + return ts.getObjectFlags(type) & 16 && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 : 4194303 : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 : 4181984 : + strictNullChecks ? 1972176 : 4184016; } if (flags & (4096 | 8192)) { return 2457472; @@ -35429,10 +36345,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 || node.kind === 184 ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 || node.kind === 184 ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 && node.initializer && @@ -35478,6 +36394,21 @@ var ts; } return links.switchTypes; } + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269) { + if (clause.expression.kind === 9) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -35520,8 +36451,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35590,8 +36521,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -35662,7 +36593,7 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { + if (flowDepth === 2000) { flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -35751,15 +36682,21 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } if (containsMatchingReference(reference, node)) { + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 || init.kind === 195)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } return undefined; @@ -35782,7 +36719,7 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -35820,6 +36757,9 @@ var ts; else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -36041,9 +36981,19 @@ var ts; if (type.flags & 1 && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 : + typeofNEFacts.get(literal.text) || 8192; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -36054,11 +37004,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 : - typeofNEFacts.get(literal.text) || 8192; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { var switchTypes = getSwitchClauseTypes(switchStatement); @@ -36076,6 +37023,47 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (!(hasDefaultClause || (type.flags & 262144))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -36270,7 +37258,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, 67216319) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, 67220415) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -36329,7 +37317,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -36530,23 +37518,23 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 194 && - container.parent.kind === 202 && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { - var className = container.parent - .left - .expression - .expression; + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } - else if ((container.kind === 194 || container.kind === 237) && + else if (isInJS && + (container.kind === 194 || container.kind === 237) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -36561,13 +37549,36 @@ var ts; var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + if (container.kind === 194 && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3) { + return container.parent + .left + .expression + .expression; + } + else if (container.kind === 154 && + container.parent.kind === 186 && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6) { + return container.parent.parent.left.expression; + } + else if (container.kind === 194 && + container.parent.kind === 273 && + container.parent.parent.kind === 186 && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287) { @@ -36718,7 +37729,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -36765,7 +37776,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -36887,10 +37898,17 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54: var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53: case 26: @@ -36899,8 +37917,8 @@ var ts; return undefined; } } - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0: return true; @@ -36916,19 +37934,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); - } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319, undefined, id.escapedText, true); - return !ts.isFunctionSymbol(parentSymbol); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415, undefined, id.escapedText, true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4: case 2: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -37105,7 +38150,7 @@ var ts; ts.Debug.assert(parent.parent.kind === 204); return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193: { - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268: @@ -37124,6 +38169,9 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -37131,7 +38179,7 @@ var ts; if (isTypeAny(valueType)) { return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -37195,11 +38243,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -37290,8 +38338,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -37323,7 +38371,7 @@ var ts; return (node.kind === 184 && !!node.initializer) || (node.kind === 202 && node.operatorToken.kind === 58); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -37333,7 +38381,7 @@ var ts; for (var index = 0; index < elementCount; index++) { var e = elements[index]; if (inDestructuringPattern && e.kind === 206) { - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1) || getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); if (restElementType) { @@ -37342,7 +38390,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206) { @@ -37376,6 +38424,9 @@ var ts; } return createTupleType(elementTypes, minLength, hasRestElement); } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } } return getArrayLiteralType(elementTypes, 2); } @@ -37442,9 +38493,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 || contextualType.pattern.kind === 186); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -37462,7 +38513,7 @@ var ts; var type = memberDecl.kind === 273 ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -37643,12 +38694,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096); var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -37665,7 +38718,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -37673,7 +38726,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0, 4096); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -37682,7 +38735,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096); } } var parent = openingLikeElement.parent.kind === 258 ? openingLikeElement.parent : undefined; @@ -37698,7 +38751,7 @@ var ts; createArrayType(getUnionType(childrenTypes)); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, propagatingFlags, 4096); } } if (hasSpreadAnyType) { @@ -37710,7 +38763,7 @@ var ts; return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.flags |= 268435456; + result.flags |= (propagatingFlags |= 268435456); result.objectFlags |= 128 | 4096; return result; } @@ -37736,7 +38789,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928); + var typeSymbol = exports && getSymbol(exports, name, 67897832); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } function getIntrinsicTagSymbol(node) { @@ -37775,7 +38828,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -37785,7 +38838,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 4 : 0); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 2 : 0); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -37842,7 +38895,7 @@ var ts; return getGlobalSymbol(JsxNames.JSX, 1920, undefined); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832); var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); if (propertiesOfJsxElementAttribPropInterface) { @@ -37859,7 +38912,7 @@ var ts; return undefined; } function getJsxLibraryManagedAttributes(jsxNamespace) { - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832); } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); @@ -38016,7 +39069,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, true); })); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { @@ -38098,7 +39151,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319, reactRefErr, reactNamespace, true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = 67108863; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -38179,10 +39232,10 @@ var ts; if (symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3; + ts.getAssignmentDeclarationKind(parent) === 3; } } function checkPropertyAccessibility(node, isSuper, type, prop) { @@ -38206,7 +39259,7 @@ var ts; } if ((flags & 128) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); return false; } @@ -38342,6 +39395,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192) && getFalsyFlags(flowType) & 8192) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); @@ -38449,7 +39508,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -38534,7 +39593,7 @@ var ts; } var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) - : ts.isInJavaScriptFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } function getForInVariableSymbol(node) { var initializer = node.initializer; @@ -38590,7 +39649,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -38598,7 +39657,14 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + if (isTupleType(objectType) && !objectType.target.hasRestElement && ts.isNumericLiteral(indexExpression)) { + var index = +indexExpression.text; + var maximumIndex = ts.length(objectType.target.typeParameters); + if (index >= maximumIndex) { + error(indexExpression, ts.Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); + } + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -38696,12 +39762,11 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; - var callIsIncomplete = false; - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { return true; } + var argCount; + var callIsIncomplete = false; if (node.kind === 191) { argCount = args.length; if (node.template.kind === 204) { @@ -38715,7 +39780,7 @@ var ts; } } else if (node.kind === 150) { - argCount = getEffectiveArgumentCount(node, undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -38724,10 +39789,10 @@ var ts; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { return false; @@ -38752,7 +39817,7 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { inferTypes(context.inferences, source, target); @@ -38760,7 +39825,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { var skipContextParamType = getTypeAtPosition(signature, 0); @@ -38796,43 +39861,36 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 208) { + var arg = args[i]; + if (arg.kind !== 208) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 | 15794176) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { return arg.kind === 213 ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1) || anyType; @@ -38840,12 +39898,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -38854,23 +39909,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -38907,28 +39962,24 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 208) { - if (i === restIndex && (restType.flags & 65536 || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } function getThisArgumentOfCall(node) { @@ -38939,10 +39990,17 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } function getEffectiveCallArguments(node) { if (node.kind === 191) { var template = node.template; - var args_4 = [undefined]; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -38950,178 +40008,70 @@ var ts; } return args_4; } - else if (node.kind === 150) { - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; - } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 150) { - switch (node.parent.kind) { - case 238: - case 207: - return 1; - case 152: - return 2; - case 154: - case 156: - case 157: - if (languageVersion === 0) { - return 2; - } - return signature.parameters.length >= 3 ? 3 : 2; - case 149: - return 3; - default: - return ts.Debug.fail(); - } - } - else { - return args.length; - } - } - function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 238) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 149) { - node = node.parent; - if (node.kind === 155) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 || - node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - return getParentTypeOfClassElement(node); + return getEffectiveDecoratorArguments(node); } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 238) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149) { - node = node.parent; - if (node.kind === 155) { - return anyType; - } + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - if (node.kind === 152 || - node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - var element = node; - var name = element.name; - switch (name.kind) { - case 71: - return getLiteralType(ts.idText(name)); - case 8: - case 9: - return getLiteralType(name.text); - case 147: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 238) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149) { - return numberType; - } - if (node.kind === 152) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 150) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191) { - return getGlobalTemplateStringsArrayType(); - } - return undefined; + return args; } - function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 150 || - (argIndex === 0 && node.kind === 191)) { - return undefined; + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238: + case 207: + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149: + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152: + case 154: + case 156: + case 157: + var hasPropDesc = parent.kind !== 152 && languageVersion !== 0; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - return args[argIndex]; + return ts.Debug.fail(); } - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150) { - return node.expression; - } - else if (argIndex === 0 && node.kind === 191) { - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238: + case 207: + return 1; + case 152: + return 2; + case 154: + case 156: + case 157: + return languageVersion === 0 || signature.parameters.length <= 2 ? 2 : 3; + case 149: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -39130,6 +40080,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -39138,7 +40089,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -39149,16 +40103,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -39190,19 +40153,7 @@ var ts; } var args = getEffectiveCallArguments(node); var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; var candidateForArgumentError; var candidateForArgumentArityError; var candidateForTypeArgumentError; @@ -39229,14 +40180,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -39256,58 +40210,67 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } - } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { - candidateForArgumentError = candidate; - break; + else { + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(true)] = false; + } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + candidateForArgumentError = checkCandidate; + continue; + } + if (excludeArgument) { + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); } - else { - excludeArgument = undefined; + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + candidateForArgumentError = checkCandidate; + continue; } } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { ts.Debug.assert(candidates.length > 0); return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) @@ -39360,17 +40323,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -39428,11 +40401,18 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0, relatedInformation); } return resolveErrorCall(node); } - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -39478,11 +40458,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -39549,10 +40531,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -39631,7 +40614,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { @@ -39681,8 +40664,8 @@ var ts; links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (node && ts.isInJSFile(node)) { if (ts.getJSDocClassTag(node)) return true; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : @@ -39692,21 +40675,21 @@ var ts; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -39719,14 +40702,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -39769,7 +40749,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -39779,7 +40759,7 @@ var ts; return anyType; } } - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -39787,8 +40767,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -39813,7 +40793,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319, undefined, undefined, false); + return globalESSymbol === resolveName(left, "Symbol", 67220415, undefined, undefined, false); } function checkImportCallExpression(node) { if (!checkGrammarArguments(node.arguments)) @@ -39868,7 +40848,7 @@ var ts; } if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319, undefined, undefined, true); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415, undefined, undefined, true); if (resolvedRequire === requireSymbol) { return true; } @@ -39991,14 +40971,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -40007,17 +40984,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -40041,21 +41008,23 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { + function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176) { - return restType; - } + return !isTupleType(restType) || restType.target.hasRestElement; } - return undefined; + return false; } - function hasEffectiveRestParameter(signature) { + function getEffectiveRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - return !isTupleType(restType) || restType.target.hasRestElement; + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } - return false; + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -40242,10 +41211,40 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0; + if (hasDefault) { + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192; + } + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192; + } + } + else { + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64; + } + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197) { + var operandType = getTypeOfExpression(node.expression.expression); + var witnesses = getSwitchClauseTypeOfWitnesses(node); + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -40290,7 +41289,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -40348,8 +41347,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -40562,8 +41563,8 @@ var ts; } if (type.flags & 786432) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40834,7 +41835,7 @@ var ts; return (target.flags & 24576) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -40963,9 +41964,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : leftType; case 58: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -40980,15 +41981,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928, undefined, name, false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832, undefined, name, false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -41033,8 +42034,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2: return true; case 1: @@ -41043,7 +42044,7 @@ var ts; case 3: case 4: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -41135,7 +42136,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266) { + if (node.kind === 266 && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; } return node; @@ -41174,9 +42175,9 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, true); var widened = ts.getCombinedNodeFlags(declaration) & 2 || - (ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576) { if (noImplicitAny) { reportImplicitAnyError(declaration, anyType); @@ -41212,11 +42213,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -41250,29 +42251,37 @@ var ts; return type; } function getTypeOfExpression(node, cache) { - if (node.kind === 189 && node.expression.kind !== 97 && !ts.isRequireCall(node, true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + var expr = ts.skipParentheses(node); + if (expr.kind === 189 && expr.expression.kind !== 97 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 || expr.kind === 210) { + return getTypeFromTypeNode(expr.type); + } return cache ? checkExpressionCached(node) : checkExpression(node); } function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1); node.contextualType = saveContextualType; return type; } - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -41287,13 +42296,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71: return checkIdentifier(node); @@ -41318,7 +42327,7 @@ var ts; case 12: return globalRegExpType; case 185: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186: return checkObjectLiteral(node, checkMode); case 187: @@ -41408,9 +42417,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); @@ -41434,7 +42440,7 @@ var ts; error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -41835,7 +42841,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -41866,7 +42872,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -42250,10 +43256,10 @@ var ts; case 246: case 249: case 248: - var result_3 = 0; + var result_4 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235: case 184: case 237: @@ -42374,7 +43380,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319, true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415, true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { @@ -42394,7 +43400,7 @@ var ts; return; } var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -42444,7 +43450,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 ? 67901928 : 1920) | 2097152; + var meaning = (typeName.kind === 71 ? 67897832 : 1920) | 2097152; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 @@ -42669,7 +43675,7 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -43091,7 +44097,7 @@ var ts; return visit(n.expression); } else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 67216319 | 2097152, undefined, undefined, false); + var symbol = resolveName(n, n.escapedText, 67220415 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -43158,7 +44164,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); markPropertyAsReferenced(property, undefined, false); - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97, parentType, property); } } @@ -43192,7 +44198,7 @@ var ts; if (node === symbol.valueDeclaration) { var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -43971,7 +44977,7 @@ var ts; } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 2162688)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -44168,6 +45174,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192); @@ -44604,8 +45612,8 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { - var excludedMeanings = (symbol.flags & (67216319 | 1048576) ? 67216319 : 0) | - (symbol.flags & 67901928 ? 67901928 : 0) | + var excludedMeanings = (symbol.flags & (67220415 | 1048576) ? 67220415 : 0) | + (symbol.flags & 67897832 ? 67897832 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 ? @@ -44615,7 +45623,7 @@ var ts; } if (compilerOptions.isolatedModules && node.kind === 255 - && !(target.flags & 67216319) + && !(target.flags & 67220415) && !(node.flags & 4194304)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -44666,13 +45674,13 @@ var ts; if (node.moduleReference.kind !== 257) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319) { + if (target.flags & 67220415) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 67220415 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928) { + if (target.flags & 67897832) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -44721,12 +45729,12 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, undefined, true); + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } @@ -44754,7 +45762,7 @@ var ts; } if (node.expression.kind === 71) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, true); } } @@ -44784,7 +45792,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -44826,7 +45834,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -44990,7 +45998,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -45195,7 +46203,7 @@ var ts; case 238: case 239: if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832); } break; case 194: @@ -45269,12 +46277,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -45299,7 +46307,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1: case 3: @@ -45325,7 +46333,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 && entityName.parent === entityName.parent.parent.left) { var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -45334,7 +46342,7 @@ var ts; } } if (entityName.parent.kind === 252 && ts.isEntityNameExpression(entityName)) { - var success = resolveEntityName(entityName, 67216319 | 67901928 | 1920 | 2097152, true); + var success = resolveEntityName(entityName, 67220415 | 67897832 | 1920 | 2097152, true); if (success && success !== unknownSymbol) { return success; } @@ -45358,9 +46366,9 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 209) { - meaning = 67901928; + meaning = 67897832; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319; + meaning |= 67220415; } } else { @@ -45376,7 +46384,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 && entityName.parent.parent.kind === 301) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); + ts.Debug.assert(!ts.isInJSFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -45389,7 +46397,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319, false, true); + return resolveEntityName(entityName, 67220415, false, true); } else if (entityName.kind === 187 || entityName.kind === 146) { var links = getNodeLinks(entityName); @@ -45406,7 +46414,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 ? 67901928 : 1920; + var meaning = entityName.parent.kind === 162 ? 67897832 : 1920; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 265) { @@ -45476,7 +46484,7 @@ var ts; case 13: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 || node.parent.kind === 253) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -45490,6 +46498,7 @@ var ts; case 79: case 89: case 36: + case 75: return getSymbolOfNode(node.parent); case 181: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -45499,14 +46508,14 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274) { - return resolveEntityName(location.name, 67216319 | 2097152); + return resolveEntityName(location.name, 67220415 | 2097152); } return undefined; } function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 | 67901928 | 1920 | 2097152); + resolveEntityName(node.propertyName || node.name, 67220415 | 67897832 | 1920 | 2097152); } function getTypeOfNode(node) { if (node.flags & 8388608) { @@ -45515,9 +46524,7 @@ var ts; if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType); } return typeFromTypeNode; } @@ -45525,8 +46532,7 @@ var ts; return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var classType = getTypeOfClassContainingHeritageClause(node); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -45558,6 +46564,9 @@ var ts; } return errorType; } + function getTypeOfClassContainingHeritageClause(node) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent)); + } function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { ts.Debug.assert(expr.kind === 186 || expr.kind === 185); if (expr.parent.kind === 225) { @@ -45593,6 +46602,22 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71: + return getLiteralType(ts.idText(name)); + case 8: + case 9: + return getLiteralType(name.text); + case 147: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); @@ -45652,13 +46677,13 @@ var ts; var symbolLinks = getSymbolLinks(moduleSymbol); if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319) + ? !!(moduleSymbol.flags & 67220415) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319); + return s && !!(s.flags & 67220415); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -45693,7 +46718,7 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); - if (isNonLocalAlias(symbol, 67216319)) { + if (isNonLocalAlias(symbol, 67220415)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -45706,7 +46731,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319, undefined, undefined, false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } else if (nodeLinks_1.flags & 131072) { @@ -45778,7 +46803,7 @@ var ts; if (target === unknownSymbol) { return true; } - return !!(target.flags & 67216319) && + return !!(target.flags & 67220415) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -45791,7 +46816,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 && target.flags & 67216319) { + if (target && ts.getModifierFlags(node) & 1 && target.flags & 67220415) { return true; } } @@ -45824,6 +46849,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -45865,8 +46909,8 @@ var ts; if (!location) return ts.TypeReferenceSerializationKind.Unknown; } - var valueSymbol = resolveEntityName(typeName, 67216319, true, false, location); - var typeSymbol = resolveEntityName(typeName, 67901928, true, false, location); + var valueSymbol = resolveEntityName(typeName, 67220415, true, false, location); + var typeSymbol = resolveEntityName(typeName, 67897832, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -45964,7 +47008,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 | 1048576 | 2097152, undefined, undefined, true); + return resolveName(location, reference.escapedText, 67220415 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -45979,18 +47023,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 && type.flags & 33554432); + return !!(type.flags & 448 && type.flags & 33554432); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 ? nodeBuilder.symbolToExpression(type.symbol, 67220415, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -46028,6 +47074,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -46078,9 +47126,9 @@ var ts; if (!fileToDirective) { return undefined; } - var meaning = 67901928 | 1920; + var meaning = 67897832 | 1920; if ((node.kind === 71 && isInTypeQuery(node)) || (node.kind === 187 && !isInHeritageClause(node))) { - meaning = 67216319 | 1048576; + meaning = 67220415 | 1048576; } var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -46158,6 +47206,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -46249,7 +47300,7 @@ var ts; for (var helper = 1; helper <= 65536; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -46617,10 +47668,31 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -46794,6 +47866,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { @@ -46818,8 +47893,9 @@ var ts; } var currentKind = void 0; switch (prop.kind) { - case 273: case 274: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + case 273: checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8) { checkGrammarNumericLiteral(name); @@ -47022,6 +48098,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -47108,24 +48187,32 @@ var ts; expr.kind === 200 && expr.operator === 38 && expr.operand.kind === 8; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 || node.initializer.kind === 86); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 && node.parent.parent.kind !== 225) { if (node.flags & 4194304) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -47259,10 +48346,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -47293,8 +48381,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 || ts.hasModifier(node, 32 | 128))) { @@ -50550,27 +51638,30 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; - function startsWithUseStrict(statements) { - var firstStatement = ts.firstOrUndefined(statements); - return firstStatement !== undefined - && ts.isPrologueDirective(firstStatement) - && isUseStrictPrologue(firstStatement); - } - ts.startsWithUseStrict = startsWithUseStrict; - function ensureUseStrict(statements) { - var foundUseStrict = false; + function findUseStrictPrologue(statements) { for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { var statement = statements_3[_i]; if (ts.isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; + return statement; } } else { break; } } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + function ensureUseStrict(statements) { + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -56995,15 +58086,21 @@ var ts; ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } function shouldEmitExplicitInitializerForLetDeclaration(node) { var flags = resolver.getNodeCheckFlags(node); var isCapturedInFunction = flags & 131072; @@ -59726,7 +60823,10 @@ var ts; var needUMDDynamicImportHelper; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 67108864 || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -59767,17 +60867,20 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createExpressionStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), - ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ - ts.createParameter(undefined, undefined, undefined, "require"), - ts.createParameter(undefined, undefined, undefined, "exports") - ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) ]), node.statements)); ts.addEmitHelpers(updated, context.readEmitHelpers()); @@ -61900,11 +63003,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -61924,7 +63027,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -61942,6 +63045,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -61951,10 +63055,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -62018,15 +63122,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -62038,6 +63143,7 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; needsDeclare = false; @@ -62055,6 +63161,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -62072,8 +63179,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -62084,11 +63192,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { if (emittedImports) { @@ -62124,13 +63235,16 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -62140,6 +63254,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71) { return name; @@ -62598,7 +63721,22 @@ var ts; return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 237: { - return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + var clean = cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, undefined); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242: { needsDeclare = false; @@ -62865,10 +64003,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235: case 152: case 151: + return !ts.hasModifier(node, 8); case 149: + case 235: return true; } return false; @@ -63885,7 +65024,7 @@ var ts; else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; @@ -63906,7 +65045,7 @@ var ts; return ".json"; } if (options.jsx === 1) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { return ".jsx"; } @@ -63987,11 +65126,11 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { nonJsFiles.forEach(collectLinkedAliases); @@ -64670,7 +65809,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -64682,7 +65821,7 @@ var ts; emitLiteral(node); } function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -65080,7 +66219,7 @@ var ts; function needsDotDotForPropertyAccess(expression) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23)); } @@ -65271,7 +66410,7 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -65935,13 +67074,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -65967,11 +67106,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -66126,7 +67270,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos - && !(ts.isArrowFunction(parentNode) && parentNode.type) + && ts.isArrowFunction(parentNode) + && !parentNode.type && !ts.some(parentNode.decorators) && !ts.some(parentNode.modifiers) && !ts.some(parentNode.typeParameters) @@ -66516,19 +67661,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } function pushNameGenerationScope(node) { if (node && ts.getEmitFlags(node) & 524288) { @@ -66683,7 +67828,7 @@ var ts; for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); - if (local && local.flags & (67216319 | 1048576 | 2097152)) { + if (local && local.flags & (67220415 | 1048576 | 2097152)) { return false; } } @@ -66748,7 +67893,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, true); } function generateNameForModuleOrEnum(node) { @@ -67189,15 +68334,20 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -67213,7 +68363,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -67223,7 +68373,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -67231,8 +68381,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); if (fingerprint && @@ -67242,8 +68392,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -67254,11 +68404,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -67270,36 +68420,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -67307,8 +68454,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -67333,7 +68480,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -67412,8 +68559,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); @@ -67428,11 +68575,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -67486,13 +68633,16 @@ var ts; } return resolutions; } - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; } @@ -67508,8 +68658,21 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -67519,16 +68682,12 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; function shouldProgramCreateNewSourceFiles(program, newOptions) { - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -67606,7 +68765,7 @@ var ts; var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { @@ -67618,11 +68777,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, false, false, undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -67698,7 +68858,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67731,7 +68893,7 @@ var ts; if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } @@ -67761,13 +68923,13 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } var unknownModuleNames; var result; @@ -67825,19 +68987,15 @@ var ts; ts.Debug.assert(j === resolutions.length); return result; function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); - if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + if (!oldProgramState.program) { return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { return false; } - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -67863,30 +69021,30 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0; } - var oldRefs = oldProgram.getProjectReferences(); + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0; + } + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0; - } + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { return oldProgram.structureIsReused = 0; } } else { - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0; - } + ts.Debug.assert(!oldRefs); } var newSourceFiles = []; var filePaths = []; @@ -67900,7 +69058,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, undefined, shouldCreateNewSourceFile); if (!newSourceFile) { return oldProgram.structureIsReused = 0; @@ -67924,6 +69082,9 @@ var ts; fileChanged = newSourceFile !== oldSourceFile; } newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -67971,7 +69132,7 @@ var ts; modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -67986,7 +69147,7 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -68018,14 +69179,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { var path = toPath(f); if (getSourceFileByPath(path)) return true; @@ -68034,11 +69202,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -68048,11 +69217,12 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { - if (!resolvedRefOpts.options.outFile) + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -68104,7 +69274,7 @@ var ts; } if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -68158,9 +69328,9 @@ var ts; } } function getSyntacticDiagnosticsForFile(sourceFile) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -68234,7 +69404,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -68447,7 +69617,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; @@ -68607,6 +69777,7 @@ var ts; return redirect; } function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames) { @@ -68679,6 +69850,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); var existingFile = filesByNameIgnoreCase.get(pathLowerCase); @@ -68706,22 +69878,22 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts") || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts") : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, false, undefined, file, ref.pos, ref.end); }); } @@ -68730,7 +69902,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -68806,7 +69978,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -68815,7 +69987,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -68828,7 +70000,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -68847,34 +70019,26 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100); if (sourceFile === undefined) { @@ -68884,22 +70048,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -68939,9 +70097,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -68950,17 +70109,16 @@ var ts; } } } - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -69009,15 +70167,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -69055,8 +70213,8 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } if (options.outDir || @@ -69067,15 +70225,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -69256,7 +70414,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts")) || !!getSourceFileByPath((filePathWithoutExtension + ".tsx")); @@ -69271,7 +70429,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -69279,13 +70440,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { @@ -69342,13 +70504,16 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } function getReferencedFileFromImportLiteral(checker, importName) { var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } function getReferencedFiles(program, sourceFile, getCanonicalFileName) { var referencedFiles; if (sourceFile.imports && sourceFile.imports.length > 0) { @@ -69365,7 +70530,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -69375,7 +70540,7 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } @@ -69769,7 +70934,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -69782,7 +70947,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -69908,16 +71080,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { getProgram: function () { return program; }, getState: ts.notImplemented, @@ -70046,7 +71218,7 @@ var ts; return primaryResult; } var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (resolvedModule) { return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; @@ -70458,87 +71630,100 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 : importModuleSpecifierPreference === "non-relative" ? 1 : 2, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0; + case "index": return 1; + case "js": return 2; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 : 0; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 : 1, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 : 0, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; - } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1) { + return nonRelative; + } + if (relativePreference !== 2) + ts.Debug.assertNever(relativePreference); + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47) + count++; } - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -70596,16 +71781,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -70623,7 +71798,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -70643,39 +71819,40 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -70744,13 +71921,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json")) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0: + return ts.removeSuffix(noExtension, "/index"); + case 1: + return noExtension; + case 2: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts": + case ".d.ts": + return ".js"; + case ".tsx": + return options.jsx === 1 ? ".jsx" : ".js"; + case ".js": + case ".jsx": + case ".json": + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); @@ -70785,16 +71985,12 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -70836,7 +72032,7 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); @@ -70848,7 +72044,7 @@ var ts; reportSemanticDiagnostics = true; } } - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -70879,6 +72075,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { if (system === void 0) { system = ts.sys; } if (!createProgram) { @@ -70888,7 +72103,7 @@ var ts; host; var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -70902,17 +72117,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -70952,18 +72160,19 @@ var ts; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -70986,7 +72195,7 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; @@ -71056,7 +72265,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -71089,9 +72299,9 @@ var ts; } } var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -71115,7 +72325,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); if (needsUpdateInTypeRootWatch) { @@ -71304,6 +72514,7 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; + projectReferences = configFileParseResult.projectReferences; configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -71395,7 +72606,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -71407,87 +72619,61 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - function createFileMap() { + function createFileMap(toPath) { var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } - } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); - } - } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); - } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; + return lookup.get(toPath(fileName)); } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; + function getSize() { + return lookup.size; } - function getKeys() { - return allKeys.getKeys(); + function clear() { + lookup.clear(); } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts"); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json") ? ".json" : @@ -71499,7 +72685,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json")) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -71510,13 +72700,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts"); + var dts = ts.changeExtension(out, ".d.ts"); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -71527,366 +72721,542 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - addProject(arg); - } - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + var unchangedOutputs = createFileMap(toPath); + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); if (cfg) { - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1)); - }); + watchWildCardDirectories(resolved, cfg); + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + return; } - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); + if (isOutputFile(fileOrDirectory, parsed)) { + return; } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + if (!ts.fileExtensionIs(fileName, ".d.ts") && + (ts.fileExtensionIs(fileName, ".ts") || ts.fileExtensionIs(fileName, ".tsx"))) { + return false; + } + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts"))) { + return true; } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; } + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); } - function resetBuildContext(opts) { - if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; } + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + if (result.fileNames.length !== 0) { + ts.filterMutate(proj.errors, function (error) { return !ts.isErrorNoInputFiles(error); }); + } + else if (!proj.configFileSpecs.filesSpecs && !ts.some(proj.errors, ts.isErrorNoInputFiles)) { + proj.errors.push(ts.getErrorForNoInputFiles(proj.configFileSpecs, resolved)); + } + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { @@ -71894,381 +73264,204 @@ var ts; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + function getFilesToClean() { + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); if (defaultOptions.dry) { - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } - function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - buildHost.verbose.apply(buildHost, [message].concat(args)); + } + function relName(path) { + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; - } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json")) { + return project; } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -72303,6 +73496,7 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: + case UpToDateStatusType.ComputingUpstream: break; default: ts.assertType(status); @@ -72310,6 +73504,131 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +var ts; +(function (ts) { + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; + } + function anyValue(name, comment) { + return { kind: 0, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.release.js.map var ts; (function (ts) { @@ -72330,7 +73649,7 @@ var ts; return !!ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY(); } function shouldBePretty(options) { - if (typeof options.pretty === "undefined") { + if (!options || typeof options.pretty === "undefined") { return defaultIsPretty(); } return options.pretty; @@ -72354,28 +73673,10 @@ var ts; ts.filter(ts.optionDeclarations.slice(), function (v) { return !!v.showInSimplifiedHelpView; }); } function executeCommandLine(args) { - if (args.length > 0 && ((args[0].toLowerCase() === "--build") || (args[0].toLowerCase() === "-b"))) { - var reportDiag_1 = ts.createDiagnosticReporter(ts.sys, defaultIsPretty()); - var report = function (message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return reportDiag_1(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); - }; - var buildHost = { - error: report, - verbose: report, - message: report, - errorDiagnostic: function (d) { return reportDiag_1(d); } - }; - var result = ts.performBuild(args.slice(1), ts.createCompilerHost({}), buildHost, ts.sys); - // undefined = in watch mode, do not exit - if (result !== undefined) { - return ts.sys.exit(result); - } - else { - return; + if (args.length > 0 && args[0].charCodeAt(0) === 45 /* minus */) { + var firstOption = args[0].slice(args[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + if (firstOption === "build" || firstOption === "b") { + return performBuild(args.slice(1)); } } var commandLine = ts.parseCommandLine(args); @@ -72467,6 +73768,42 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } + function performBuild(args) { + var _a = ts.parseBuildCommand(args), buildOptions = _a.buildOptions, projects = _a.projects, errors = _a.errors; + if (errors.length > 0) { + errors.forEach(reportDiagnostic); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.help) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + // Update to pretty if host supports it + updateReportDiagnostic(); + if (projects.length === 0) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + if (!ts.sys.getModifiedTime || !ts.sys.setModifiedTime || (buildOptions.clean && !ts.sys.deleteFile)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.watch) { + reportWatchModeWithoutSysSupport(); + } + // TODO: change this to host if watch => watchHost otherwiue without wathc + var builder = ts.createSolutionBuilder(ts.createSolutionBuilderWithWatchHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()), projects, buildOptions); + if (buildOptions.clean) { + return ts.sys.exit(builder.cleanAllProjects()); + } + if (buildOptions.watch) { + builder.buildAllProjects(); + return builder.startWatching(); + } + return ts.sys.exit(builder.buildAllProjects()); + } function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { var host = ts.createCompilerHost(options); enableStatistics(options); @@ -72484,12 +73821,12 @@ var ts; } function updateWatchCompilationHost(watchCompilerHost) { var compileUsingBuilder = watchCompilerHost.createProgram; - watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { ts.Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { enableStatistics(options); } - return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics); + return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = function (builderProgram) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 4111b40028b34..d5a660813271e 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -88,7 +88,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -101,6 +101,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -729,17 +730,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -784,7 +791,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1161,7 +1168,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1281,6 +1288,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1948,6 +1959,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2042,6 +2057,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2747,38 +3122,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -3006,9 +3381,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3027,22 +3401,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3809,17 +4183,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4755,7 +5133,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4794,6 +5172,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5037,7 +5419,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5065,6 +5446,13 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5156,6 +5544,8 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + Index_0_is_out_of_bounds_in_tuple_of_length_1: diag(2733, ts.DiagnosticCategory.Error, "Index_0_is_out_of_bounds_in_tuple_of_length_1_2733", "Index '{0}' is out-of-bounds in tuple of length {1}."), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5269,7 +5659,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5363,7 +5755,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5461,6 +5853,14 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5491,9 +5891,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5558,6 +5958,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5686,6 +6087,8 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; @@ -6407,6 +6810,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6436,6 +6840,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6891,6 +7296,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6929,6 +7335,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6986,6 +7410,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7568,6 +7997,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7588,7 +8020,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7670,22 +8101,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7790,6 +8208,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8014,12 +8438,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8046,13 +8478,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8421,6 +8853,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -9148,18 +9584,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9199,14 +9635,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9229,15 +9665,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9245,26 +9685,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9273,7 +9713,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9287,30 +9727,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9321,7 +9761,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9365,12 +9805,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9380,9 +9820,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9411,7 +9851,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9420,11 +9860,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9530,7 +9970,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9572,6 +10012,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9762,6 +10206,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9786,32 +10236,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9870,7 +10324,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9879,7 +10333,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10627,7 +11081,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10748,7 +11202,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10764,7 +11218,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11120,10 +11574,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11262,6 +11716,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11352,6 +11828,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11527,6 +12005,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11538,12 +12018,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11769,13 +12271,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12103,13 +12598,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12121,9 +12616,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12131,10 +12624,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12165,7 +12656,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12211,15 +12702,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12240,6 +12730,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12366,7 +12873,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13712,7 +14232,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14105,6 +14625,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14121,9 +14653,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14135,13 +14666,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14414,8 +14946,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14637,6 +15167,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14923,31 +15460,36 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; @@ -15080,14 +15622,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15258,6 +15800,10 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; })(ts || (ts = {})); var ts; (function (ts) { @@ -15346,6 +15892,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15416,6 +15963,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15774,7 +16322,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15943,8 +16491,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -17380,8 +17932,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19477,8 +20031,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -21074,7 +21629,7 @@ var ts; nextJSDocToken(); } } - function skipWhitespaceOrAsterisk() { + function skipWhitespaceOrAsterisk(next) { if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range @@ -21088,7 +21643,7 @@ var ts; else if (token() === 39 /* AsteriskToken */) { precedingLineBreak = false; } - nextJSDocToken(); + next(); } } function parseTag(indent) { @@ -21096,8 +21651,9 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespaceOrAsterisk(); + // Use 'nextToken' instead of 'nextJsDocToken' so we can parse a type like 'number' in `@enum number` + var tagName = parseJSDocIdentifierName(/*message*/ undefined, nextToken); + skipWhitespaceOrAsterisk(nextToken); var tag; switch (tagName.escapedText) { case "augments": @@ -21234,7 +21790,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21268,7 +21824,7 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { @@ -21277,10 +21833,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21294,14 +21848,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21389,7 +21943,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(nextJSDocToken); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21404,7 +21958,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21465,7 +22019,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21505,17 +22059,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21543,7 +22097,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21569,9 +22123,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -21624,7 +22176,8 @@ var ts; } return entity; } - function parseJSDocIdentifierName(message) { + function parseJSDocIdentifierName(message, next) { + if (next === void 0) { next = nextJSDocToken; } if (!ts.tokenIsIdentifierOrKeyword(token())) { return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } @@ -21633,7 +22186,7 @@ var ts; var result = createNode(71 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); - nextJSDocToken(); + next(); return result; } } @@ -22412,8 +22965,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +22979,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22474,21 +23062,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22503,6 +23076,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22521,6 +23096,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22533,6 +23109,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22540,6 +23117,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22557,6 +23135,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22666,6 +23245,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23254,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,6 +23263,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22690,6 +23272,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22698,6 +23281,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23290,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23324,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23337,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22758,6 +23345,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22767,6 +23355,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22782,6 +23371,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22793,6 +23383,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22803,6 +23394,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22887,30 +23479,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22969,12 +23543,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22987,6 +23563,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23032,6 +23609,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23039,6 +23617,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23066,6 +23645,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23093,7 +23673,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23146,20 +23764,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23195,16 +23814,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23216,7 +23834,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23224,7 +23842,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23260,7 +23878,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +23921,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23318,7 +23946,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23939,7 +24595,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23956,8 +24613,21 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + if (filesSpecs.length === 0 && hasZeroOrNoReferences) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23998,14 +24668,13 @@ var ts; } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24013,7 +24682,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24123,11 +24791,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24174,7 +24837,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24182,7 +24845,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24396,7 +25059,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24459,12 +25122,8 @@ var ts; } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24653,6 +25312,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24669,7 +25334,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24678,48 +25343,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); } - return; } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); } - return path; + return; } + return result; } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24763,7 +25474,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24783,7 +25495,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24810,11 +25521,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24830,7 +25541,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24869,11 +25580,11 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { // Return just the type directive names result.push(ts.getBaseFileName(normalized)); @@ -25099,15 +25810,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25145,7 +25856,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25164,7 +25875,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25175,74 +25886,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25254,8 +25951,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25263,7 +25960,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25277,7 +25974,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25294,29 +25991,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25324,7 +26022,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25365,52 +26063,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25424,12 +26116,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25443,40 +26135,41 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); - } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state); if (fromPackageJson) { return fromPackageJson; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(candidate, state.host); + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25488,6 +26181,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25499,23 +26193,24 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); + function loadModuleFromPackageJson(jsonContent, versionPaths, extensions, candidate, state) { + var file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) + : readPackageJsonMainField(jsonContent, candidate, state); if (!file) { if (extensions === Extensions.TypeScript) { // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + file = readPackageJsonMainField(jsonContent, candidate, state); if (!file) { return undefined; } @@ -25524,26 +26219,35 @@ var ts; return undefined; } } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailures = !ts.directoryProbablyExists(ts.getDirectoryPath(file), state.host); + if (versionPaths && ts.containsPath(candidate, file)) { + var moduleName = ts.getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state)); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25563,87 +26267,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25651,11 +26397,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25664,43 +26410,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25708,24 +26455,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25740,9 +26487,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25957,13 +26704,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -26008,7 +26759,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26088,7 +26839,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26166,12 +26918,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26432,6 +27184,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -27230,7 +27984,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27250,7 +28004,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27338,9 +28092,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27360,7 +28111,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27585,7 +28336,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27632,7 +28383,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27649,15 +28400,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27730,15 +28481,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27754,7 +28505,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27765,9 +28516,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27848,14 +28599,18 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { @@ -27914,7 +28669,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27944,7 +28699,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -28001,7 +28756,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28022,7 +28777,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28048,40 +28803,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28090,7 +28844,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28103,7 +28857,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28187,8 +28941,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28200,10 +28957,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28220,7 +28977,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28238,10 +28995,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28279,10 +29036,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28291,14 +29048,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28317,9 +29074,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28357,7 +29112,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28395,6 +29150,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -29447,6 +30205,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29467,7 +30237,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29683,8 +30454,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29752,7 +30523,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29782,8 +30554,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29946,6 +30731,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29988,6 +30775,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30123,35 +30911,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30184,7 +30972,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30197,8 +30985,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30237,12 +31026,12 @@ var ts; var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); @@ -30259,7 +31048,7 @@ var ts; } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); }); } @@ -30373,8 +31162,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30517,7 +31306,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30526,7 +31315,7 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + if (meaning & 67220415 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { // parameters are visible only inside function body, parameter list and return type // technically for parameter list case here we might mix parameters and variables declared in function, // however it is detected separately when checking initializers of parameters @@ -30612,7 +31401,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30622,7 +31411,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30649,7 +31441,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30669,7 +31461,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30752,7 +31544,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30807,14 +31599,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30910,9 +31702,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30931,29 +31723,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30981,6 +31776,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31050,7 +31848,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31104,7 +31902,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31194,7 +31992,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31213,7 +32011,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31228,10 +32026,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31262,7 +32060,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31311,7 +32109,7 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -31324,11 +32122,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31344,7 +32142,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31379,15 +32177,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31395,9 +32193,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31405,6 +32215,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31434,7 +32251,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32270,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31485,7 +32302,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31493,7 +32310,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31505,18 +32322,17 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; @@ -31750,7 +32566,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31850,7 +32666,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31900,7 +32716,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31965,11 +32784,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -32007,7 +32826,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32115,7 +32944,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32125,7 +32954,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32275,13 +33104,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32301,7 +33130,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32368,14 +33197,14 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; @@ -32448,23 +33277,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32546,8 +33375,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32586,7 +33415,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32599,7 +33428,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32697,18 +33526,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32836,7 +33660,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32847,7 +33671,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32888,6 +33712,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32897,6 +33724,16 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. @@ -33009,7 +33846,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33017,7 +33861,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33174,7 +34018,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33358,10 +34202,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33382,7 +34226,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33431,6 +34275,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33683,7 +34529,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33714,16 +34560,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33743,16 +34595,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33766,8 +34618,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33775,9 +34627,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33785,7 +34637,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33803,8 +34655,8 @@ var ts; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33823,7 +34675,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33837,10 +34689,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33889,8 +34741,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33898,7 +34750,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -34050,7 +34902,14 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { return checkExpression(declaration.expression); @@ -34060,9 +34919,9 @@ var ts; return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34076,7 +34935,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34137,7 +34996,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34195,7 +35054,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34223,7 +35082,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34232,11 +35091,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34261,7 +35120,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34270,22 +35129,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34444,15 +35295,15 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { + var isJavascript = ts.isInJSFile(location); + if (isJSConstructorType(type) && !typeArgCount) { return getSignaturesOfType(type, 0 /* Call */); } return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); @@ -34460,7 +35311,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34542,8 +35393,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34642,7 +35493,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34781,9 +35632,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -35009,7 +35860,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35029,7 +35880,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35283,7 +36134,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35778,10 +36629,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35798,7 +36654,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35877,6 +36734,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35884,8 +36742,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35907,8 +36775,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35923,7 +36791,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35933,9 +36801,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35985,6 +36850,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35992,14 +36871,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36205,7 +37085,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36305,7 +37185,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36318,7 +37198,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36355,7 +37235,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36386,7 +37266,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36473,7 +37353,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36550,7 +37430,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36569,8 +37449,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36611,7 +37495,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36805,7 +37689,7 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; @@ -36838,7 +37722,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36893,14 +37777,28 @@ var ts; if (type) { return type; } + // JS are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36908,7 +37806,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36924,10 +37822,6 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); - } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -37042,10 +37936,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -37100,10 +37994,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37157,7 +38051,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37346,10 +38240,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37364,15 +38255,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37418,7 +38300,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37446,7 +38328,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37543,10 +38425,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37555,8 +38434,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37810,7 +38689,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37823,7 +38702,7 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; @@ -37882,7 +38761,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37900,7 +38779,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37908,20 +38790,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37935,37 +38803,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37986,7 +38841,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38013,17 +38869,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38201,7 +39068,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38231,7 +39098,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38245,7 +39112,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38387,8 +39254,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38398,7 +39265,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38604,7 +39471,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38705,7 +39572,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38715,7 +39582,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38774,8 +39641,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38785,30 +39662,24 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); - } + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38871,49 +39742,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } - } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38987,7 +39874,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39062,33 +39949,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39097,15 +40049,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39114,10 +40066,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39128,13 +40080,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39168,8 +40123,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39201,9 +40156,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39252,8 +40212,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39283,9 +40243,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39308,11 +40269,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39338,13 +40299,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39508,10 +40469,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39646,10 +40607,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39705,13 +40666,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39810,7 +40768,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39820,32 +40778,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39863,7 +40795,7 @@ var ts; return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39908,6 +40840,9 @@ var ts; } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39936,7 +40871,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39963,6 +40899,14 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -40153,6 +41097,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40181,20 +41156,24 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K] + if (relation !== identityRelation) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40212,7 +41191,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40285,6 +41263,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40318,36 +41316,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40370,10 +41358,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40504,33 +41492,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40562,8 +41523,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40755,6 +41716,33 @@ var ts; return false; } } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41043,8 +42031,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41120,10 +42108,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41148,13 +42136,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41166,7 +42158,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41180,11 +42172,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41470,19 +42463,23 @@ var ts; function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) : + sourceRestType ? targetCount : + Math.min(sourceCount, targetCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41797,6 +42794,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41832,7 +42832,14 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41928,33 +42935,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); - } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41964,12 +42976,15 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -42000,8 +43015,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42024,7 +43039,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42042,7 +43057,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42055,10 +43070,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42069,16 +43083,17 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { - if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & 32768 /* Never */)) { + // If we have contravariant inferences, but no covariant inferences or a single + // covariant inference of 'never', we find the best common subtype and treat that + // as a single covariant candidate. + inference.candidates = [getContravariantInference(inference)]; inference.contraCandidates = undefined; } if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + inferredType = getCovariantInference(inference, signature); } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42095,7 +43110,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42124,11 +43139,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42302,6 +43346,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42310,8 +43366,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42319,8 +43382,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42357,13 +43420,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42489,10 +43554,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42538,6 +43603,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42580,8 +43662,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42661,8 +43743,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42742,8 +43824,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42846,11 +43928,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42859,6 +43941,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42882,7 +43972,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42927,6 +44018,9 @@ var ts; else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43185,12 +44279,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43201,11 +44305,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43224,6 +44325,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43449,7 +44626,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43522,7 +44699,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43781,31 +44958,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43820,13 +44995,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -44052,7 +45254,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44109,7 +45311,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44225,7 +45427,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44246,13 +45448,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44262,9 +45471,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44282,19 +45491,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); - } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44513,7 +45749,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44532,6 +45768,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44540,7 +45782,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44612,11 +45854,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44722,8 +45964,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44759,7 +46001,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44781,7 +46023,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44790,7 +46032,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44828,6 +46070,9 @@ var ts; } return createTupleType(elementTypes, minLength, hasRestElement); } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } @@ -44920,9 +46165,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44940,7 +46185,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45150,12 +46395,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45172,7 +46419,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45180,7 +46427,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45189,7 +46436,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45211,7 +46458,7 @@ var ts; createArrayType(getUnionType(childrenTypes)); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45228,7 +46475,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45261,7 +46508,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45309,7 +46556,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45319,7 +46566,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45386,7 +46633,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45410,7 +46657,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45632,7 +46879,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45748,7 +46995,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45869,10 +47116,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45917,7 +47164,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46072,6 +47319,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46185,7 +47438,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46290,7 +47543,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46356,7 +47609,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46364,7 +47617,14 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + if (isTupleType(objectType) && !objectType.target.hasRestElement && ts.isNumericLiteral(indexExpression)) { + var index = +indexExpression.text; + var maximumIndex = ts.length(objectType.target.typeParameters); + if (index >= maximumIndex) { + error(indexExpression, ts.Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); + } + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46485,16 +47745,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46512,7 +47769,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46523,11 +47780,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46558,7 +47815,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46567,7 +47824,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46625,58 +47882,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46684,12 +47923,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46698,23 +47934,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46769,36 +48005,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46812,19 +48039,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46832,283 +48060,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; - } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); - } - } - else { - return args.length; - } - } - /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. - */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); + return getEffectiveDecoratorArguments(node); } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. - */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return args; } /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - return args[argIndex]; + return ts.Debug.fail(); } /** - * Gets the error node to use when reporting errors for an effective argument. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47117,6 +48149,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47125,7 +48158,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47136,16 +48172,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47178,36 +48223,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47277,14 +48306,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47304,60 +48336,74 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } - } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; - } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47427,17 +48473,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47510,12 +48566,19 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47588,11 +48651,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47662,10 +48727,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47758,7 +48824,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47837,8 +48903,8 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (node && ts.isInJSFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; @@ -47850,21 +48916,21 @@ var ts; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47877,14 +48943,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47937,7 +49000,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47948,7 +49011,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47958,8 +49021,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47985,7 +49048,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48044,7 +49107,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48169,14 +49232,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48185,17 +49245,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48219,21 +49269,23 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { + function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } + return !isTupleType(restType) || restType.target.hasRestElement; } - return undefined; + return false; } - function hasEffectiveRestParameter(signature) { + function getEffectiveRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - return !isTupleType(restType) || restType.target.hasRestElement; + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } - return false; + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -48437,10 +49489,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48490,7 +49593,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48569,8 +49672,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48816,8 +49921,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -49118,7 +50223,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49256,9 +50361,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49273,15 +50378,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49334,8 +50439,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +50449,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49450,7 +50555,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49492,9 +50597,9 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { if (noImplicitAny) { reportImplicitAnyError(declaration, anyType); @@ -49535,11 +50640,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49586,15 +50691,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49608,9 +50717,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49621,13 +50734,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49646,13 +50759,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49677,7 +50790,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49770,9 +50883,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49802,7 +50912,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50268,7 +51378,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50299,7 +51409,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50640,6 +51750,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50697,13 +51814,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50733,10 +51843,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50966,7 +52076,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50989,7 +52099,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51046,7 +52156,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51315,7 +52425,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51801,7 +52911,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51884,7 +52994,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51924,7 +53034,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51940,7 +53050,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52901,7 +54011,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -53127,6 +54237,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53616,8 +54728,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53628,7 +54740,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53681,14 +54793,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53742,13 +54854,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53779,7 +54891,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53811,7 +54923,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53859,7 +54971,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54026,7 +55138,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54273,7 +55385,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54358,12 +55470,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54388,7 +55500,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54414,7 +55526,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54426,7 +55538,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54452,10 +55564,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54471,7 +55583,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54485,7 +55597,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54502,7 +55614,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54581,7 +55693,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54597,6 +55709,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54606,7 +55719,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54614,7 +55727,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { @@ -54624,9 +55737,7 @@ var ts; if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType); } return typeFromTypeNode; } @@ -54636,8 +55747,7 @@ var ts; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var classType = getTypeOfClassContainingHeritageClause(node); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54671,6 +55781,9 @@ var ts; } return errorType; } + function getTypeOfClassContainingHeritageClause(node) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent)); + } // Gets the type of object literal or array literal of destructuring assignment. // { a } from // for ( { a } of elems) { @@ -54732,6 +55845,22 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { @@ -54799,13 +55928,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54854,7 +55983,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54867,7 +55996,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -54963,7 +56092,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54976,7 +56105,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55021,6 +56150,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55065,9 +56213,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55169,7 +56317,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55184,18 +56332,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55238,6 +56388,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55293,9 +56445,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55384,6 +56536,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55491,7 +56646,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55865,11 +57020,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56047,6 +57223,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56090,8 +57269,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56308,6 +57489,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56404,26 +57588,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56563,10 +57753,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56597,8 +57788,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60174,6 +61365,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60187,19 +61393,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -69210,19 +70404,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. if (node.transformFlags & 8388608 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -73529,7 +74731,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 67108864 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73583,6 +74788,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73613,22 +74819,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -76821,11 +78029,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76851,7 +78059,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76869,6 +78077,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76878,10 +78087,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76950,15 +78159,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76970,6 +78180,7 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76987,6 +78198,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -77005,8 +78217,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77017,11 +78230,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77059,13 +78275,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77075,6 +78296,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77591,10 +78821,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77878,10 +79123,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79124,7 +80370,7 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; @@ -79149,7 +80395,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79242,12 +80488,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79976,7 +81222,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79998,7 +81244,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80423,7 +81669,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80634,7 +81880,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81337,13 +82585,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81369,11 +82617,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81538,7 +82791,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81959,19 +83213,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82150,7 +83404,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82229,7 +83483,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82743,17 +83997,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82769,7 +84030,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82779,7 +84040,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82787,8 +84048,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82799,8 +84060,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82811,11 +84072,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82827,36 +84088,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82864,8 +84122,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82891,7 +84149,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82979,8 +84237,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82995,11 +84253,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83057,7 +84315,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83066,6 +84324,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83086,8 +84348,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83097,21 +84375,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83209,7 +84483,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83221,11 +84495,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83312,7 +84587,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83346,9 +84623,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83391,13 +84668,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83482,8 +84759,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83491,15 +84771,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83529,15 +84802,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83545,16 +84823,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83577,7 +84854,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83604,7 +84881,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83670,7 +84951,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83686,7 +84967,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83721,14 +85003,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83739,11 +85028,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83753,12 +85043,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83815,7 +85106,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83881,9 +85172,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83972,7 +85263,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84201,7 +85492,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84384,6 +85675,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84470,6 +85762,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84499,24 +85792,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84526,7 +85821,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84613,7 +85908,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84622,7 +85917,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84642,7 +85937,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84662,27 +85957,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84690,7 +85977,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84701,22 +85988,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84756,9 +86037,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84768,17 +86050,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84828,15 +86109,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84876,9 +86157,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84893,15 +86174,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85092,7 +86373,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85109,7 +86390,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85117,17 +86401,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85197,7 +86478,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85207,6 +86488,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85230,7 +86517,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85241,7 +86528,7 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } @@ -85765,7 +87052,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85778,7 +87065,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85952,16 +87246,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86110,7 +87404,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86588,121 +87882,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); - } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; - } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86766,16 +88056,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86793,7 +88073,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86813,25 +88094,27 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86840,20 +88123,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86936,13 +88217,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86981,11 +88285,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86994,7 +88293,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87044,7 +88343,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87060,7 +88359,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87094,6 +88393,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87106,7 +88424,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87120,17 +88438,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87179,18 +88490,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87213,7 +88525,7 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; @@ -87286,7 +88598,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87324,9 +88637,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87351,7 +88664,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87563,6 +88876,7 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -87650,6 +88964,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87670,7 +88986,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87687,94 +89004,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } - } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); - } - } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); - } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; + return lookup.get(toPath(fileName)); } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; + function getSize() { + return lookup.size; } - function getKeys() { - return allKeys.getKeys(); + function clear() { + lookup.clear(); } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87787,7 +89075,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87798,13 +89090,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87815,386 +89111,598 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } + watchWildCardDirectories(resolved, cfg); // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } + watchInputFiles(resolved, cfg); } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); } } - function resetBuildContext(opts) { - if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); - } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + if (result.fileNames.length !== 0) { + ts.filterMutate(proj.errors, function (error) { return !ts.isErrorNoInputFiles(error); }); + } + else if (!proj.configFileSpecs.filesSpecs && !ts.some(proj.errors, ts.isErrorNoInputFiles)) { + proj.errors.push(ts.getErrorForNoInputFiles(proj.configFileSpecs, resolved)); + } + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { @@ -88203,420 +89711,221 @@ var ts; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; - } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88652,7 +89961,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88660,6 +89971,142 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.js.map "use strict"; var __assign = (this && this.__assign) || function () { @@ -88735,6 +90182,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -88950,8 +90421,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89008,7 +90480,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89130,6 +90602,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89260,7 +90739,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89624,7 +91103,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -89642,8 +91121,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_1 && findRightmostToken(candidate_1, sourceFile); } else { // candidate should be in this node @@ -89651,15 +91130,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -89881,7 +91358,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -89995,7 +91472,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90003,7 +91480,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90514,7 +91991,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90522,11 +91999,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -91671,9 +93148,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_1 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_1(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -91687,27 +93197,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_1 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_1(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -91722,8 +93220,8 @@ var ts; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; _loop_2(moduleName); } } @@ -91833,7 +93331,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -91866,7 +93364,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -91890,6 +93388,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -91997,11 +93507,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92102,7 +93613,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92110,22 +93621,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92137,14 +93649,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92209,6 +93721,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92294,11 +93809,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92306,16 +93822,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92328,11 +93849,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92346,7 +93867,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92373,6 +93894,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -92781,7 +94307,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -92803,6 +94332,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -92811,6 +94341,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -92948,7 +94479,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -92963,9 +94494,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93002,7 +94531,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93030,12 +94559,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93054,7 +94583,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93075,7 +94604,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93105,7 +94634,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93129,6 +94658,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + resolvedModuleSymbol.declarations.some(function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93364,7 +94900,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93398,14 +94935,16 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; } } return undefined; @@ -93559,10 +95098,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93574,6 +95110,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93782,17 +95320,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -93815,7 +95355,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -93887,7 +95427,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94379,9 +95919,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94426,7 +95963,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94440,7 +95977,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94507,6 +96044,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -94943,7 +96483,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95088,6 +96628,14 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); function nodeEntry(node, isInString) { return { type: "node", node: node.name || node, isInString: isInString }; } @@ -95152,28 +96700,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_1 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_1 = def.node; return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_2 = def.node; var name_2 = ts.tokenToString(node_2.kind); return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_3 = def.node; var symbol = checker.getSymbolAtLocation(node_3); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")]; return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_4 = def.node; return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95202,7 +96750,7 @@ var ts; textSpan: getTextSpan(node, sourceFile), isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString, }; @@ -95266,7 +96814,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95356,7 +96959,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95525,7 +97128,7 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; @@ -95801,7 +97404,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -95828,7 +97431,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96233,7 +97836,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96291,8 +97894,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96304,7 +97908,7 @@ var ts; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } @@ -96471,14 +98075,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96574,7 +98178,7 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); var _loop_3 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); @@ -96602,7 +98206,7 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; @@ -96632,16 +98236,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -96655,7 +98266,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -96697,7 +98308,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -96963,6 +98574,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97173,7 +98794,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97206,7 +98827,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97269,7 +98890,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97329,7 +98950,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97721,7 +99342,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -99425,9 +101046,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99436,9 +101057,34 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + localizedErrorMessage: undefined, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, localizedErrorMessage: undefined, @@ -99513,17 +101159,26 @@ var ts; return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99532,17 +101187,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99559,12 +101218,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99581,9 +101240,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -99895,10 +101554,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -99909,11 +101571,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -99967,7 +101646,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100091,13 +101770,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100120,7 +101799,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_1 = decl.symbol; if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) { @@ -100170,7 +101849,7 @@ var ts; var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100195,10 +101874,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100208,7 +101887,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100227,22 +101906,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100375,13 +102077,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100519,7 +102224,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -100749,7 +102454,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -100821,7 +102526,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -100888,6 +102594,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -103787,7 +105494,7 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } @@ -103825,7 +105532,7 @@ var ts; this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -103893,24 +105600,31 @@ var ts; }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -103933,7 +105647,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104058,7 +105772,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104090,7 +105804,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104098,22 +105812,22 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; @@ -104172,9 +105886,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104200,14 +105921,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); - return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + return applyChanges(nonFormattedText, changes); } - changesToText.newFileChanges = newFileChanges; + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104245,7 +105970,7 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } })(changesToText || (changesToText = {})); @@ -105030,7 +106755,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105083,30 +106808,41 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } @@ -105117,19 +106853,14 @@ var ts; changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } var _loop_10 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; @@ -105180,7 +106911,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105194,6 +106925,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105207,19 +106939,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105227,6 +106965,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105249,9 +106988,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105261,23 +106998,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || []).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { return []; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105286,6 +107032,7 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } + codeActionSucceeded = false; return []; } function transformCatch(node, transformer, prevArgName) { @@ -105301,17 +107048,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105327,6 +107075,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105338,14 +107091,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105354,50 +107104,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return ts.createNodeArray([ts.createStatement(rightHandSide)]); + } if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); } return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; - var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + } + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, argName ? [argName.identifier] : []); if (shouldReturn) { return ts.createNodeArray([ts.createReturn(synthCall)]); } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105406,47 +107173,59 @@ var ts; } } return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return ts.createNodeArray(innerCbBody); } - if (hasPrevArgName && !shouldReturn) { + if (!shouldReturn) { var type_1 = transformer.checker.getTypeAtLocation(func); var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } return ts.createNodeArray([]); } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } return ts.createNodeArray(ret); } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { @@ -105468,12 +107247,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105481,20 +107254,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105572,7 +107343,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -105689,7 +107460,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106175,33 +107946,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); } } }); return result; } function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + return !(s.flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106262,24 +108040,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106321,7 +108099,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106373,13 +108151,9 @@ var ts; } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106389,7 +108163,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && { symbol: symbol, symbolForMeaning: info.symbolForMeaning, name: info.name, kind: kind }; + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106397,11 +108186,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -106640,10 +108429,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -106682,7 +108471,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -106782,7 +108571,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -106792,7 +108581,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -106912,7 +108701,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -106922,24 +108713,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -107676,7 +109577,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -107808,22 +109709,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -107833,7 +109731,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -107932,7 +109830,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return undefined; // TODO: GH#20113 } var token = ts.getTokenAtPosition(sourceFile, start); @@ -108381,16 +110279,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_1 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_1.set(name, symbol); }); } @@ -108406,17 +110306,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -108636,7 +110536,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -108662,6 +110562,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109757,7 +111857,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -109973,7 +112073,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110307,7 +112407,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110677,7 +112777,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111401,7 +113501,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112154,7 +114254,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112496,8 +114596,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112534,6 +114635,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112555,7 +114660,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -112670,7 +114775,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113020,19 +115125,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -114826,6 +116943,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -114870,8 +116988,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -114946,7 +117064,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -115031,7 +117149,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -115160,71 +117278,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); //# sourceMappingURL=jsTyping.js.map "use strict"; var __assign = (this && this.__assign) || function () { @@ -115251,6 +117304,15 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; var ts; (function (ts) { var server; @@ -115699,7 +117761,7 @@ var ts; var text; var fileName = tempFileName || this.fileName; var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; - if (!ts.hasTypeScriptFileExtension(this.fileName)) { + if (!ts.hasTSFileExtension(this.fileName)) { var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > server.maxFileSize) { ts.Debug.assert(!!this.info.containingProjects.length); @@ -115983,6 +118045,7 @@ var ts; server.nullTypingsInstaller = { isKnownTypesPackageName: ts.returnFalse, installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -116042,6 +118105,9 @@ var ts; TypingsCache.prototype.installPackage = function (options) { return this.installer.installPackage(options); }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -116159,6 +118225,7 @@ var ts; this.lastReportedVersion = 0; this.projectProgramVersion = 0; this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; this.dirty = false; this.hasChangedAutomaticTypeDirectiveNames = false; this.typingFiles = server.emptyArray; @@ -116219,6 +118286,9 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -116299,6 +118369,9 @@ var ts; Project.prototype.readFile = function (fileName) { return this.projectService.host.readFile(fileName); }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; Project.prototype.fileExists = function (file) { var path = this.toPath(file); return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); @@ -116458,7 +118531,7 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } - var projectReferences = this.program.getProjectReferences(); + var projectReferences = this.program.getResolvedProjectReferences(); if (projectReferences) { for (var _b = 0, projectReferences_1 = projectReferences; _b < projectReferences_1.length; _b++) { var ref = projectReferences_1[_b]; @@ -116520,7 +118593,7 @@ var ts; return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { - var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); return scriptInfo; }); @@ -116812,7 +118885,9 @@ var ts; } }; Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - server.updateProjectIfDirty(this); + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -116860,9 +118935,8 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; - Project.prototype.enableGlobalPlugins = function () { + Project.prototype.enableGlobalPlugins = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -116945,7 +119019,7 @@ var ts; if (!projectRootPath && !projectService.useSingleInferredProject) { _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); } - _this.enableGlobalPlugins(); + _this.enableGlobalPlugins(_this.getCompilerOptions()); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -117017,27 +119091,32 @@ var ts; server.InferredProject = InferredProject; var ConfiguredProject = (function (_super) { __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; - _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectReferences = projectReferences; + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); - _this.enablePlugins(); return _this; } ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: - return this.projectService.reloadFileNamesOfConfiguredProject(this); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; case ts.ConfigFileProgramReloadLevel.Full: this.projectService.reloadConfiguredProject(this); - return true; + result = true; + break; default: - return _super.prototype.updateGraph.call(this); + result = _super.prototype.updateGraph.call(this); } + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; }; ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { return this.directoryStructureHost; @@ -117053,11 +119132,13 @@ var ts; }; ConfiguredProject.prototype.getResolvedProjectReferences = function () { var program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.getResolvedProjectReferences(); }; ConfiguredProject.prototype.enablePlugins = function () { + this.enablePluginsWithOptions(this.getCompilerOptions()); + }; + ConfiguredProject.prototype.enablePluginsWithOptions = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117074,7 +119155,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths); } } - this.enableGlobalPlugins(); + this.enableGlobalPlugins(options); }; ConfiguredProject.prototype.getGlobalProjectErrors = function () { return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; @@ -117131,6 +119212,9 @@ var ts; } return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; @@ -117154,6 +119238,12 @@ var ts; _this.excludedFiles = []; return _this; } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; @@ -117179,6 +119269,7 @@ var ts; server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; server.maxFileSize = 4 * 1024 * 1024; server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.SurveyReady = "surveyReady"; server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -117266,6 +119357,11 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -117308,6 +119404,7 @@ var ts; WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { @@ -117325,14 +119422,23 @@ var ts; function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } var ProjectService = (function () { function ProjectService(opts) { var _this = this; this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); this.filenameToScriptInfoVersion = ts.createMap(); this.allJsFilesForOpenFileTelemetry = ts.createMap(); this.externalProjectToConfiguredProjectMap = ts.createMap(); @@ -117348,6 +119454,7 @@ var ts; this.legacySafelist = {}; this.pendingProjectUpdates = ts.createMap(); this.seenProjects = ts.createMap(); + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117360,7 +119467,7 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); if (this.host.realpath) { @@ -117507,6 +119614,12 @@ var ts; }; this.eventHandler(event); }; + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { if (!this.eventHandler) { return; @@ -118011,33 +120124,6 @@ var ts; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); - var result = ts.parseJsonText(configFilename, configFileContent); - if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 }; - } - var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); - if (parsedCommandLine.errors.length) { - errors.push.apply(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, - configHasFilesProperty: parsedCommandLine.raw.files !== undefined, - configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, - wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), - typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave, - projectReferences: parsedCommandLine.projectReferences - }; - return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; - }; ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { return; @@ -118049,12 +120135,12 @@ var ts; for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var f = fileNames_1[_i]; var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { + if (ts.hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); return fileName; } } @@ -118065,9 +120151,9 @@ var ts; return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); } function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .filter(function (name) { return hasTSFileExtension(name); }) .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); @@ -118077,21 +120163,35 @@ var ts; var compilerOptions = convertCompilerOptions(options); var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(projectFileName, project); return project; }; - ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { - if (this.seenProjects.has(projectKey)) { + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { + return; + } + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); return; } - this.seenProjects.set(projectKey, true); + this.seenProjects.set(project.projectName, true); if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); return; } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); var data = { - projectId: this.host.createSHA256Hash(projectKey), + projectId: this.host.createSHA256Hash(project.projectName), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -118110,8 +120210,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; - return server.getBaseConfigFileName(configFilePath) || "other"; + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -118122,31 +120221,73 @@ var ts; }; } }; - ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); - project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); - var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); - project.configFileSpecs = configFileSpecs; + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); - if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); - } - project.setProjectErrors(configFileErrors); - var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); - this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + return project; + }; + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project); + return project; + }; + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName) { + var project = this.createAndLoadConfiguredProject(configFileName); + project.updateGraph(); + return project; + }; + ProjectService.prototype.loadConfiguredProject = function (project) { + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); + } + project.enablePluginsWithOptions(compilerOptions); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); @@ -118194,19 +120335,19 @@ var ts; } project.markAsDirty(); }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { var configFileSpecs = project.configFileSpecs; var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); - this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; ProjectService.prototype.reloadConfiguredProject = function (project) { @@ -118214,20 +120355,8 @@ var ts; host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); - var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; - project.configFileSpecs = configFileSpecs; - project.setProjectErrors(configFileErrors); - project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - } - else { - project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); - } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.loadConfiguredProject(project); + project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -118354,10 +120483,77 @@ var ts; if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } } }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1, "node_modules for closed script infos in them"); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -118416,6 +120612,7 @@ var ts; return this.filenameToScriptInfo.get(fileName); }; ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { @@ -118433,7 +120630,18 @@ var ts; this.logger.info("Format host information updated"); } if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + _this.loadConfiguredProject(project); + project.updateGraph(); + } + }); + } } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; @@ -118467,12 +120675,8 @@ var ts; ts.Debug.assert(info.isScriptOpen()); var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { - var project = _this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - _this.createConfiguredProject(configFileName); - updatedProjects.set(configFileName, true); - } - else if (!updatedProjects.has(configFileName)) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; _this.delayUpdateProjectGraph(project); @@ -118527,7 +120731,7 @@ var ts; var configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createAndLoadConfiguredProject(configFileName); updateProjectIfDirty(configuredProject); addOriginalConfiguredProject(configuredProject); var originalScriptInfo = this.getScriptInfo(fileName); @@ -118567,7 +120771,7 @@ var ts; if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName); if (info.isOrphan()) { configFileName = undefined; } @@ -118895,7 +121099,8 @@ var ts; else { externalProject.enableLanguageService(); } - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); return; } this.closeExternalProject(proj.projectFileName); @@ -118935,7 +121140,9 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - project = this.createConfiguredProject(tsconfigFile); + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { project.addExternalProjectReference(); @@ -118944,7 +121151,8 @@ var ts; } else { this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); } }; ProjectService.prototype.hasDeferredExtension = function () { @@ -119137,7 +121345,7 @@ var ts; }; } server.toEvent = toEvent; - function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + function combineProjectOutput(defaultValue, getValue, projects, action) { var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { @@ -119145,9 +121353,7 @@ var ts; outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); }); } - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); + return ts.deduplicate(outputs, ts.equateValues); } function combineProjectOutputFromEveryProject(projectService, action, areEqual) { var outputs = []; @@ -119190,17 +121396,19 @@ var ts; } function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; var _loop_8 = function (outputReferencedSymbol) { - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition: definition, references: [] }; outputs.push(symbolToAddTo); } for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { var ref = _a[_i]; - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } @@ -119261,7 +121469,7 @@ var ts; seenProjects.set(projectAndLocation.project.projectName, true); var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); if (!originalLocation) - return false; + return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { @@ -119277,7 +121485,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -119659,6 +121867,10 @@ var ts; diagnostics: bakedDiags }, "configFileDiag"); break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, "surveyReady"); + break; case server.ProjectLanguageServiceStateEvent: { var eventName = "projectLanguageServiceState"; this.event({ @@ -120136,12 +122348,12 @@ var ts; if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; - Session.mapRenameInfo = function (_a) { - var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; - return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + Session.prototype.mapRenameInfo = function (_a, scriptInfo) { + var canRename = _a.canRename, fileToRename = _a.fileToRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers, triggerSpan = _a.triggerSpan; + return { canRename: canRename, fileToRename: fileToRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }; }; Session.prototype.toSpanGroups = function (locations) { var map = ts.createMap(); @@ -120368,7 +122580,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (completions === undefined) return undefined; if (kind === "completions-full") @@ -120708,8 +122920,8 @@ var ts; var commands = args.command; for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - var project = this.getFileAndProject(command).project; - project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); } return {}; }; @@ -121840,13 +124052,18 @@ var ts; }; NodeTypingsInstaller.prototype.installPackage = function (options) { var _this = this; - var rq = __assign({ kind: "installPackage" }, options); - this.send(rq); + this.send(__assign({ kind: "installPackage" }, options)); ts.Debug.assert(this.packageInstalledPromise === undefined); return new Promise(function (resolve, reject) { _this.packageInstalledPromise = { resolve: resolve, reject: reject }; }); }; + NodeTypingsInstaller.prototype.inspectValue = function (options) { + var _this = this; + this.send({ kind: "inspectValue", options: options }); + ts.Debug.assert(this.inspectValuePromise === undefined); + return new Promise(function (resolve) { _this.inspectValuePromise = { resolve: resolve }; }); + }; NodeTypingsInstaller.prototype.attach = function (projectService) { var _this = this; this.projectService = projectService; @@ -121945,6 +124162,10 @@ var ts; this.event(response, "setTypings"); break; } + case server.ActionValueInspected: + this.inspectValuePromise.resolve(response.result); + this.inspectValuePromise = undefined; + break; case server.EventInitializationFailed: { var body = { @@ -122190,13 +124411,16 @@ var ts; var cmdLineLogFileName = server.findArgument("--logFile"); var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity")); var envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); - var logFileName = cmdLineLogFileName + var unsubstitutedLogFileName = cmdLineLogFileName ? ts.stripQuotes(cmdLineLogFileName) : envLogOptions.logToFile ? envLogOptions.file || (__dirname + "/.log" + process.pid.toString()) : undefined; + var substitutedLogFileName = unsubstitutedLogFileName + ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) + : undefined; var logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel; - return new Logger(logFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 + return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 } // This places log file in the directory containing editorServices.js // TODO: check that this location is writable @@ -122414,7 +124638,7 @@ var ts; } sys.require = function (initialDir, moduleName) { try { - return { module: require(ts.resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; + return { module: require(ts.resolveJSModule(moduleName, initialDir, sys)), error: undefined }; } catch (error) { return { module: undefined, error: error }; @@ -122442,7 +124666,7 @@ var ts; } ts.setStackTraceLimit(); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); // TODO: GH#18217 - var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(sys.getExecutingFilePath(), "../typesMap.json"); + var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(ts.getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); var npmLocation = server.findArgument(server.Arguments.NpmLocation); function parseStringArray(argName) { var arg = server.findArgument(argName); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index a16288c6c2725..21ee605120a2f 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -536,6 +536,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +633,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +670,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1808,7 +1811,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2060,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2581,7 +2585,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2595,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2693,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2993,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3211,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4183,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4316,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4385,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4394,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4430,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4441,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4454,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4662,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4720,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4884,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5268,6 +5113,11 @@ declare namespace ts { } interface RenameInfo { canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; localizedErrorMessage?: string; displayName: string; fullDisplayName: string; @@ -5751,24 +5601,6 @@ declare namespace ts.server { remove(path: NormalizedPath): void; } function createNormalizedPathMap(): NormalizedPathMap; - interface ProjectOptions { - configHasExtendsProperty: boolean; - /** - * true if config file explicitly listed files - */ - configHasFilesProperty: boolean; - configHasIncludeProperty: boolean; - configHasExcludeProperty: boolean; - projectReferences: ReadonlyArray | undefined; - /** - * these fields can be present in the project file - */ - files?: string[]; - wildcardDirectories?: Map; - compilerOptions?: CompilerOptions; - typeAcquisition?: TypeAcquisition; - compileOnSave?: boolean; - } function isInferredProjectName(name: string): boolean; function makeInferredProjectName(counter: number): string; function createSortedArray(): SortedArray; @@ -6607,6 +6439,11 @@ declare namespace ts.server.protocol { * True if item can be renamed. */ canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; /** * Error message if item can not be renamed. */ @@ -6627,6 +6464,8 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; } /** * A group of text spans, all in 'file'. @@ -7148,7 +6987,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions; + command: CommandTypes.Completions | CommandTypes.CompletionInfo; arguments: CompletionsRequestArgs; } /** @@ -7660,6 +7499,15 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } type LargeFileReferencedEventName = "largeFileReferenced"; interface LargeFileReferencedEvent extends Event { event: LargeFileReferencedEventName; @@ -7995,6 +7843,7 @@ declare namespace ts.server.protocol { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -8126,14 +7975,14 @@ declare namespace ts.server { getSnapshot(): IScriptSnapshot; private ensureRealPath; getFormatCodeSettings(): FormatCodeSettings | undefined; - getPreferences(): UserPreferences | undefined; + getPreferences(): protocol.UserPreferences | undefined; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; detachFromProject(project: Project): void; detachAllProjects(): void; getDefaultProject(): Project; registerFileUpdate(): void; - setOptions(formatSettings: FormatCodeSettings, preferences: UserPreferences | undefined): void; + setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; getLatestVersion(): string; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): boolean; @@ -8238,6 +8087,7 @@ declare namespace ts.server { * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project */ private projectStateVersion; + protected isInitialLoadPending: () => boolean; private readonly cancellationToken; isNonTsProject(): boolean; isJsOnlyProject(): boolean; @@ -8261,6 +8111,7 @@ declare namespace ts.server { useCaseSensitiveFileNames(): boolean; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile(fileName: string): string | undefined; + writeFile(fileName: string, content: string): void; fileExists(file: string): boolean; resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -8322,7 +8173,7 @@ declare namespace ts.server { filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(): void; + protected enableGlobalPlugins(options: CompilerOptions): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ refreshDiagnostics(): void; @@ -8351,14 +8202,14 @@ declare namespace ts.server { * Otherwise it will create an InferredProject. */ class ConfiguredProject extends Project { - compileOnSaveEnabled: boolean; - private projectReferences; private typeAcquisition; private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; /** Ref count to the project when opened from external project */ private externalProjectRefCount; private projectErrors; + private projectReferences; + protected isInitialLoadPending: () => boolean; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph * @returns: true if set of files in the project stays the same and false - otherwise. @@ -8391,6 +8242,7 @@ declare namespace ts.server { compileOnSaveEnabled: boolean; excludedFiles: ReadonlyArray; private typeAcquisition; + updateGraph(): boolean; getExcludedFiles(): ReadonlyArray; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; @@ -8399,6 +8251,7 @@ declare namespace ts.server { declare namespace ts.server { const maxProgramSizeForNonTsFiles: number; const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + const SurveyReady = "surveyReady"; const LargeFileReferencedEvent = "largeFileReferenced"; const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -8410,6 +8263,12 @@ declare namespace ts.server { openFiles: string[]; }; } + interface SurveyReady { + eventName: typeof SurveyReady; + data: { + surveyId: string; + }; + } interface LargeFileReferencedEvent { eventName: typeof LargeFileReferencedEvent; data: { @@ -8488,7 +8347,7 @@ declare namespace ts.server { interface OpenFileInfo { readonly checkJs: boolean; } - type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { @@ -8509,7 +8368,7 @@ declare namespace ts.server { function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; - preferences: UserPreferences; + preferences: protocol.UserPreferences; hostInfo: string; extraFileExtensions?: FileExtensionInfo[]; } @@ -8538,6 +8397,7 @@ declare namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo; + private readonly scriptInfoInNodeModulesWatchers; /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -8607,6 +8467,8 @@ declare namespace ts.server { readonly syntaxOnly?: boolean; /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; + /** Tracks projects that we have already sent survey events for. */ + private readonly seenSurveyProjects; constructor(opts: ProjectServiceOptions); toPath(fileName: string): Path; private loadTypesMap; @@ -8628,9 +8490,9 @@ declare namespace ts.server { */ private ensureProjectStructuresUptoDate; getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; - getPreferences(file: NormalizedPath): UserPreferences; + getPreferences(file: NormalizedPath): protocol.UserPreferences; getHostFormatCodeOptions(): FormatCodeSettings; - getHostPreferences(): UserPreferences; + getHostPreferences(): protocol.UserPreferences; private onSourceFileChanged; private handleDeletedFile; private onConfigChangedForConfiguredProject; @@ -8692,15 +8554,13 @@ declare namespace ts.server { private findConfiguredProjectByProjectName; private getConfiguredProjectByCanonicalConfigFilePath; private findExternalProjectByProjectName; - private convertConfigFileContentToProjectOptions; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ private getFilenameForExceededTotalSizeLimitForNonTsFiles; private createExternalProject; - private sendProjectTelemetry; - private addFilesToNonInferredProjectAndUpdateGraph; + private addFilesToNonInferredProject; private createConfiguredProject; private updateNonInferredProjectFiles; - private updateNonInferredProject; + private updateRootAndOptionsOfNonInferredProject; private sendConfigFileDiagEvent; private getOrCreateInferredProjectForProjectRootPathIfEnabled; private getOrCreateSingleInferredProjectIfEnabled; @@ -8708,6 +8568,10 @@ declare namespace ts.server { private createInferredProject; getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; private watchClosedScriptInfo; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; private stopWatchingScriptInfo; private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; private getOrCreateScriptInfoOpenedByClientForNormalizedPath; @@ -8881,7 +8745,7 @@ declare namespace ts.server { private getProjects; private getDefaultProject; private getRenameLocations; - private static mapRenameInfo; + private mapRenameInfo; private toSpanGroups; private getReferences; /** diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 19046c62c9ab7..8c1d755206eed 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -69,13 +69,22 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -88,6 +97,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +726,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +787,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1164,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1284,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1935,6 +1955,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2053,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2734,38 +3118,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2993,9 +3377,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3397,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3796,17 +4179,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4742,7 +5129,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5168,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5415,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5442,13 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5540,8 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + Index_0_is_out_of_bounds_in_tuple_of_length_1: diag(2733, ts.DiagnosticCategory.Error, "Index_0_is_out_of_bounds_in_tuple_of_length_1_2733", "Index '{0}' is out-of-bounds in tuple of length {1}."), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5655,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5751,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5849,14 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5887,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5954,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,6 +6083,8 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; @@ -6394,6 +6806,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6836,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6878,6 +7292,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7331,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7406,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7555,6 +7993,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +8016,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8097,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8204,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8434,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8474,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8849,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -9135,18 +9580,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9631,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9661,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9681,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9709,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9723,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9757,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9801,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9816,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9847,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9856,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9966,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +10008,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10202,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10232,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10320,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10329,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10614,7 +11077,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11198,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11214,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11107,10 +11570,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11712,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11824,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +12001,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +12014,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12267,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12594,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12612,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12620,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12652,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12698,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12726,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12869,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14228,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14621,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14649,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14662,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14942,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15163,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14910,31 +15456,36 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; @@ -15067,14 +15618,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15796,10 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15888,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15959,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16318,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16487,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -17367,8 +17928,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +20027,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -21061,7 +21625,7 @@ var ts; nextJSDocToken(); } } - function skipWhitespaceOrAsterisk() { + function skipWhitespaceOrAsterisk(next) { if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range @@ -21075,7 +21639,7 @@ var ts; else if (token() === 39 /* AsteriskToken */) { precedingLineBreak = false; } - nextJSDocToken(); + next(); } } function parseTag(indent) { @@ -21083,8 +21647,9 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespaceOrAsterisk(); + // Use 'nextToken' instead of 'nextJsDocToken' so we can parse a type like 'number' in `@enum number` + var tagName = parseJSDocIdentifierName(/*message*/ undefined, nextToken); + skipWhitespaceOrAsterisk(nextToken); var tag; switch (tagName.escapedText) { case "augments": @@ -21221,7 +21786,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21255,7 +21820,7 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { @@ -21264,10 +21829,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21844,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21939,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(nextJSDocToken); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21954,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +22015,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22055,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22093,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22119,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -21611,7 +22172,8 @@ var ts; } return entity; } - function parseJSDocIdentifierName(message) { + function parseJSDocIdentifierName(message, next) { + if (next === void 0) { next = nextJSDocToken; } if (!ts.tokenIsIdentifierOrKeyword(token())) { return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } @@ -21620,7 +22182,7 @@ var ts; var result = createNode(71 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); - nextJSDocToken(); + next(); return result; } } @@ -22399,8 +22961,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22975,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23058,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23072,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23092,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23105,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23113,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23131,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23241,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23250,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,6 +23259,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22677,6 +23268,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23277,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23286,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23320,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23333,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23341,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23351,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23367,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23379,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23390,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23475,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23539,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23559,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23605,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23613,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23641,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23669,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23760,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23810,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23830,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23838,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23874,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23917,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23942,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23926,7 +24591,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24609,21 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + if (filesSpecs.length === 0 && hasZeroOrNoReferences) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23985,14 +24664,13 @@ var ts; } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24678,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24110,11 +24787,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24833,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24841,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25055,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24446,12 +25118,8 @@ var ts; } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25308,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25330,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25339,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); } - return; } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); } - return path; + return; } + return result; } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25470,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25491,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25517,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25537,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,11 +25576,11 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { // Return just the type directive names result.push(ts.getBaseFileName(normalized)); @@ -25086,15 +25806,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25852,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25871,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25882,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25947,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25956,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +25970,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +25987,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26018,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26059,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26112,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26131,41 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); - } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state); if (fromPackageJson) { return fromPackageJson; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(candidate, state.host); + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26177,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,23 +26189,24 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); + function loadModuleFromPackageJson(jsonContent, versionPaths, extensions, candidate, state) { + var file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) + : readPackageJsonMainField(jsonContent, candidate, state); if (!file) { if (extensions === Extensions.TypeScript) { // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + file = readPackageJsonMainField(jsonContent, candidate, state); if (!file) { return undefined; } @@ -25511,26 +26215,35 @@ var ts; return undefined; } } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailures = !ts.directoryProbablyExists(ts.getDirectoryPath(file), state.host); + if (versionPaths && ts.containsPath(candidate, file)) { + var moduleName = ts.getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state)); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26263,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26393,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26406,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26451,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26483,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26700,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26755,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26835,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26914,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26419,6 +27180,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -27217,7 +27980,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28000,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28088,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28107,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28332,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28379,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28396,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28477,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28501,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28512,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,14 +28595,18 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { @@ -27901,7 +28665,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28695,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28752,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28773,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28799,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28840,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28853,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28937,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28953,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28973,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +28991,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29032,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29044,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29070,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29108,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28382,6 +29146,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -29434,6 +30201,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30233,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29670,8 +30450,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30519,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30550,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29933,6 +30727,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30771,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30907,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30968,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +30981,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30224,12 +31022,12 @@ var ts; var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); @@ -30246,7 +31044,7 @@ var ts; } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); }); } @@ -30360,8 +31158,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31302,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,7 +31311,7 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + if (meaning & 67220415 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { // parameters are visible only inside function body, parameter list and return type // technically for parameter list case here we might mix parameters and variables declared in function, // however it is detected separately when checking initializers of parameters @@ -30599,7 +31397,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31407,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31437,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31457,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30739,7 +31540,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31595,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31698,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31719,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30968,6 +31772,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31844,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31898,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31181,7 +31988,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +32007,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32022,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32056,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,7 +32105,7 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -31311,11 +32118,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32138,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32173,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32189,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32211,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32247,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32266,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32298,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32306,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,18 +32318,17 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; @@ -31737,7 +32562,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32662,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32712,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32780,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32822,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32940,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32950,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32262,13 +33100,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33126,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,14 +33193,14 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; @@ -32435,23 +33273,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33371,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33411,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33424,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33522,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33656,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33667,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33708,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,6 +33720,16 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. @@ -32996,7 +33842,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33857,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33161,7 +34014,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34198,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34222,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34271,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33670,7 +34525,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34556,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34591,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34614,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34623,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34633,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33790,8 +34651,8 @@ var ts; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34671,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34685,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33876,8 +34737,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34746,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -34037,7 +34898,14 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { return checkExpression(declaration.expression); @@ -34047,9 +34915,9 @@ var ts; return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34931,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +34992,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34182,7 +35050,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35078,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35087,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35116,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35125,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,15 +35291,15 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { + var isJavascript = ts.isInJSFile(location); + if (isJSConstructorType(type) && !typeArgCount) { return getSignaturesOfType(type, 0 /* Call */); } return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); @@ -34447,7 +35307,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34529,8 +35389,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35489,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35628,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35856,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35876,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36130,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35765,10 +36625,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36650,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36730,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36738,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36771,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36787,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36797,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36846,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36867,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36192,7 +37081,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37181,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37194,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37231,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37262,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37349,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36537,7 +37426,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37445,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37491,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,7 +37685,7 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; @@ -36825,7 +37718,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37773,28 @@ var ts; if (type) { return type; } + // JS are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37802,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36911,10 +37818,6 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); - } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -37029,10 +37932,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -37087,10 +37990,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37144,7 +38047,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37333,10 +38236,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38251,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38296,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38324,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38421,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38430,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38685,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,7 +38698,7 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; @@ -37869,7 +38757,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38775,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38786,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38799,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38837,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38865,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39064,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39094,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39108,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39250,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39261,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39467,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39568,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39578,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39637,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39658,24 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); - } + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38858,49 +39738,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } - } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39870,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39049,33 +39945,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40045,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40062,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40076,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40119,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40152,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40208,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40239,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40265,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40295,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40465,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40603,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40662,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40764,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40774,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39850,7 +40791,7 @@ var ts; return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39895,6 +40836,9 @@ var ts; } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40867,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,6 +40895,14 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -40140,6 +41093,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41152,24 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K] + if (relation !== identityRelation) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41187,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41259,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41312,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41354,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41488,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41519,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41712,33 @@ var ts; return false; } } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42027,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41107,10 +42104,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42132,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42154,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42168,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41457,19 +42459,23 @@ var ts; function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) : + sourceRestType ? targetCount : + Math.min(sourceCount, targetCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41784,6 +42790,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42828,14 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +42931,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); - } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +42972,15 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43011,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43035,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43053,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43066,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43079,17 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { - if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & 32768 /* Never */)) { + // If we have contravariant inferences, but no covariant inferences or a single + // covariant inference of 'never', we find the best common subtype and treat that + // as a single covariant candidate. + inference.candidates = [getContravariantInference(inference)]; inference.contraCandidates = undefined; } if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + inferredType = getCovariantInference(inference, signature); } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43106,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43135,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42289,6 +43342,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43362,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43378,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43416,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42476,10 +43550,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43599,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42567,8 +43658,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43739,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43820,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +43924,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +43937,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +43968,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42914,6 +44014,9 @@ var ts; else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44275,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44301,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44321,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43436,7 +44622,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43509,7 +44695,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43768,31 +44954,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +44991,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -44039,7 +45250,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45307,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44212,7 +45423,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45444,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45467,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45487,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); - } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44500,7 +45745,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45764,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45778,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +45850,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +45960,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +45997,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46019,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46028,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44815,6 +46066,9 @@ var ts; } return createTupleType(elementTypes, minLength, hasRestElement); } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } @@ -44907,9 +46161,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46181,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46391,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46415,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46423,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46432,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45198,7 +46454,7 @@ var ts; createArrayType(getUnionType(childrenTypes)); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46471,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46504,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46552,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46562,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46629,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46653,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +46875,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +46991,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47112,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47160,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47315,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47434,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47539,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47605,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47613,14 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + if (isTupleType(objectType) && !objectType.target.hasRestElement && ts.isNumericLiteral(indexExpression)) { + var index = +indexExpression.text; + var maximumIndex = ts.length(objectType.target.typeParameters); + if (index >= maximumIndex) { + error(indexExpression, ts.Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); + } + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47741,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47765,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47776,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47811,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47820,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +47878,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +47919,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +47930,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +48001,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48035,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48056,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; - } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); - } + return getEffectiveDecoratorArguments(node); } - else { - return args.length; - } - } - /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. - */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. - */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return args; } /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - return args[argIndex]; + return ts.Debug.fail(); } /** - * Gets the error node to use when reporting errors for an effective argument. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48145,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48154,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48168,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48219,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48302,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48332,74 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } - } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; - } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47414,17 +48469,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47497,12 +48562,19 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48647,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48723,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47745,7 +48820,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,8 +48899,8 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (node && ts.isInJSFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; @@ -47837,21 +48912,21 @@ var ts; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +48939,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +48996,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +49007,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49017,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49044,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49103,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49228,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49241,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,21 +49265,23 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { + function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } + return !isTupleType(restType) || restType.target.hasRestElement; } - return undefined; + return false; } - function hasEffectiveRestParameter(signature) { + function getEffectiveRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - return !isTupleType(restType) || restType.target.hasRestElement; + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } - return false; + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -48424,10 +49485,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49589,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48556,8 +49668,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48803,8 +49917,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -49105,7 +50219,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50357,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50374,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50435,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50445,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50551,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,9 +50593,9 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { if (noImplicitAny) { reportImplicitAnyError(declaration, anyType); @@ -49522,11 +50636,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50687,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50713,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50730,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50755,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50786,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +50879,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +50908,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51374,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51405,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50627,6 +51746,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51810,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +51839,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52072,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52095,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52152,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51302,7 +52421,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +52907,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +52990,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53030,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53046,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52888,7 +54007,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -53114,6 +54233,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54724,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54736,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54789,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +54850,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +54887,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +54919,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +54967,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55134,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54260,7 +55381,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55466,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55496,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55522,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55534,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55560,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55579,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55593,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55610,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55689,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55705,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55715,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,7 +55723,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { @@ -54611,9 +55733,7 @@ var ts; if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType); } return typeFromTypeNode; } @@ -54623,8 +55743,7 @@ var ts; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var classType = getTypeOfClassContainingHeritageClause(node); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54658,6 +55777,9 @@ var ts; } return errorType; } + function getTypeOfClassContainingHeritageClause(node) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent)); + } // Gets the type of object literal or array literal of destructuring assignment. // { a } from // for ( { a } of elems) { @@ -54719,6 +55841,22 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { @@ -54786,13 +55924,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +55979,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,7 +55992,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -54950,7 +56088,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56101,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56146,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56209,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56313,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56328,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56384,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55280,9 +56441,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56532,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55478,7 +56642,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57016,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57219,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57265,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57485,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57584,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57749,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57784,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61361,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61389,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -69197,19 +70400,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. if (node.transformFlags & 8388608 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -73516,7 +74727,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 67108864 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +74784,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +74815,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -76808,11 +78025,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78055,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78073,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78083,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78155,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,6 +78176,7 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76974,6 +78194,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78213,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78226,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77046,13 +78271,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78292,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +78817,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77865,10 +79119,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79111,7 +80366,7 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; @@ -79136,7 +80391,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79229,12 +80484,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81218,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81240,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +81665,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +81876,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +82581,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +82613,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +82787,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83209,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83400,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +83479,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +83993,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84026,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84036,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84044,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84056,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84068,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84084,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84118,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84145,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84233,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84249,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84311,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84320,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84344,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84371,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83196,7 +84479,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +84491,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +84583,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +84619,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +84664,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +84755,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +84767,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +84798,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +84819,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +84850,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +84877,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +84947,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +84963,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +84999,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85024,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85039,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85102,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85168,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85259,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +85488,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84371,6 +85671,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84457,6 +85758,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +85788,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +85817,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +85904,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +85913,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +85933,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +85953,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +85973,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +85984,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86033,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86046,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86105,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84863,9 +86153,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86170,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86369,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86386,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86397,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +86474,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +86484,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +86513,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,7 +86524,7 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } @@ -85752,7 +87048,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87061,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87242,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87400,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86575,121 +87878,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); - } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; - } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88052,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88069,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88090,27 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +88119,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86923,13 +88213,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88281,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88289,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88339,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88355,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88389,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88420,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +88434,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +88486,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,7 +88521,7 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; @@ -87273,7 +88594,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +88633,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +88660,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87550,6 +88872,7 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -87637,6 +88960,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +88982,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +89000,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; } - } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); - } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); + function clear() { + lookup.clear(); } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89071,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89086,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,386 +89107,598 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } + watchWildCardDirectories(resolved, cfg); // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } + watchInputFiles(resolved, cfg); } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); } } - function resetBuildContext(opts) { - if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); - } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + if (result.fileNames.length !== 0) { + ts.filterMutate(proj.errors, function (error) { return !ts.isErrorNoInputFiles(error); }); + } + else if (!proj.configFileSpecs.filesSpecs && !ts.some(proj.errors, ts.isErrorNoInputFiles)) { + proj.errors.push(ts.getErrorForNoInputFiles(proj.configFileSpecs, resolved)); + } + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { @@ -88190,420 +89707,221 @@ var ts; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; - } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +89957,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +89969,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90112,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90157,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90233,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90318,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90356,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +90447,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +90496,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +90735,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +90794,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +90916,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91053,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91417,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +91435,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +91444,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +91672,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +91786,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +91794,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90883,7 +92305,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92313,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -91273,7 +92695,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +92704,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +93462,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_9 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_9(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +93511,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +93528,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_10 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_10(moduleName); } } if (!foundGlobal) { @@ -92202,7 +93645,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +93678,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +93702,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +93821,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92471,7 +93927,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +93935,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +93963,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94035,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94123,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94136,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94163,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94181,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94208,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +94621,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +94646,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +94655,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +94793,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +94808,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +94845,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +94873,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +94897,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +94918,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +94948,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +94972,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + resolvedModuleSymbol.declarations.some(function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95214,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95249,16 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; } } return undefined; @@ -93928,10 +95412,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +95424,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -94151,17 +95634,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +95669,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +95741,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94748,9 +96233,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96277,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96291,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96358,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +96646,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +96677,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +96797,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,6 +96942,14 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); function nodeEntry(node, isInString) { return { type: "node", node: node.name || node, isInString: isInString }; } @@ -95490,9 +96983,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95521,28 +97014,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95571,7 +97064,7 @@ var ts; textSpan: getTextSpan(node, sourceFile), isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString, }; @@ -95635,7 +97128,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95725,7 +97273,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95894,7 +97442,7 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; @@ -96062,8 +97610,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +97660,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +97718,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +97745,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96602,7 +98150,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98208,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96673,7 +98222,7 @@ var ts; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } @@ -96777,8 +98326,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +98389,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +98492,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_11 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +98520,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_11(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +98550,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +98580,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +98622,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +98888,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99108,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99141,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99204,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99264,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99307,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_12 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99317,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_12(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99332,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +99656,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -99248,13 +100814,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_13 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_13(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +101360,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,9 +101371,34 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + localizedErrorMessage: undefined, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, localizedErrorMessage: undefined, @@ -99882,17 +101473,26 @@ var ts; return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +101501,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +101532,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +101554,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100239,7 +101843,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + var _loop_14 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100249,7 +101853,7 @@ var ts; } }; for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + var state_4 = _loop_14(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +101868,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +101885,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +101960,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102084,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102113,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100539,7 +102163,7 @@ var ts; var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102188,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102201,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102220,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +102391,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +102538,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +102768,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +102840,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +102908,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +102982,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_15 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +103001,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_15(opt); } return options; } @@ -104156,7 +105808,7 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } @@ -104194,7 +105846,7 @@ var ts; this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104262,24 +105914,31 @@ var ts; }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +105961,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106086,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106118,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106126,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_16 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106161,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_16(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106200,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106218,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_17 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_17(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106235,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); - return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + return applyChanges(nonFormattedText, changes); } - changesToText.newFileChanges = newFileChanges; + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,7 +106284,7 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } })(changesToText || (changesToText = {})); @@ -105399,7 +107069,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,30 +107122,41 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } @@ -105485,24 +107166,19 @@ var ts; var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_18 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_18(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107225,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107239,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107253,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107279,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107302,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107312,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || []).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { return []; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,6 +107346,7 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } + codeActionSucceeded = false; return []; } function transformCatch(node, transformer, prevArgName) { @@ -105670,17 +107362,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +107389,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +107405,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +107418,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return ts.createNodeArray([ts.createStatement(rightHandSide)]); + } if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); } return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; - var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + } + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, argName ? [argName.identifier] : []); if (shouldReturn) { return ts.createNodeArray([ts.createReturn(synthCall)]); } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105775,47 +107487,59 @@ var ts; } } return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return ts.createNodeArray(innerCbBody); } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + if (!shouldReturn) { + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } return ts.createNodeArray([]); } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } return ts.createNodeArray(ret); } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { @@ -105837,12 +107561,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +107568,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +107657,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +107774,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108260,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); } } }); return result; } function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + return !(s.flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +108354,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +108413,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106742,13 +108465,9 @@ var ts; } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +108477,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && { symbol: symbol, symbolForMeaning: info.symbolForMeaning, name: info.name, kind: kind }; + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +108500,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +108743,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +108785,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +108814,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_19 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +108841,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_19(info); } }); })); @@ -107151,7 +108885,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +108895,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109015,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109027,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +109891,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110023,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110045,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108301,7 +110144,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return undefined; // TODO: GH#20113 } var token = ts.getTokenAtPosition(sourceFile, start); @@ -108750,16 +110593,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +110620,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +110850,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +110876,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +111526,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_20 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +111545,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_20(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112171,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +112387,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +112721,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +112777,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_21 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +112817,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_21(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113091,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111322,10 +113367,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_22 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_23 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +113392,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_23(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_22(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +113815,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +114389,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +114568,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +114910,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +114949,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +114974,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115089,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115132,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113389,19 +115439,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -115715,7 +117777,7 @@ var ts; var fileName = tempFileName || this.fileName; var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; // Only non typescript files have size limitation - if (!ts.hasTypeScriptFileExtension(this.fileName)) { + if (!ts.hasTSFileExtension(this.fileName)) { var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > server.maxFileSize) { ts.Debug.assert(!!this.info.containingProjects.length); @@ -116030,6 +118092,7 @@ var ts; isKnownTypesPackageName: ts.returnFalse, // Should never be called because we never provide a types registry. installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -116091,6 +118154,9 @@ var ts; TypingsCache.prototype.installPackage = function (options) { return this.installer.installPackage(options); }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -116236,6 +118302,7 @@ var ts; * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project */ this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; /*@internal*/ this.dirty = false; /*@internal*/ @@ -116301,6 +118368,10 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + /* @internal */ + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -116385,6 +118456,9 @@ var ts; Project.prototype.readFile = function (fileName) { return this.projectService.host.readFile(fileName); }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; Project.prototype.fileExists = function (file) { // As an optimization, don't hit the disks for files we already know don't exist // (because we're watching for their creation). @@ -116568,7 +118642,7 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } - var projectReferences = this.program.getProjectReferences(); + var projectReferences = this.program.getResolvedProjectReferences(); if (projectReferences) { for (var _b = 0, projectReferences_2 = projectReferences; _b < projectReferences_2.length; _b++) { var ref = projectReferences_2[_b]; @@ -116639,7 +118713,7 @@ var ts; return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { - var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); return scriptInfo; }); @@ -116949,8 +119023,8 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { - var file = sourceFiles_9[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var file = sourceFiles_7[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -116973,7 +119047,10 @@ var ts; }; /* @internal */ Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - server.updateProjectIfDirty(this); + // Update the graph only if initial configured project load is not pending + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -117026,9 +119103,8 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; - Project.prototype.enableGlobalPlugins = function () { + Project.prototype.enableGlobalPlugins = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117037,7 +119113,7 @@ var ts; // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_26 = function (globalPluginName) { + var _loop_24 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -117052,7 +119128,7 @@ var ts; // Enable global plugins with synthetic configuration entries for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_26(globalPluginName); + _loop_24(globalPluginName); } } }; @@ -117127,7 +119203,7 @@ var ts; if (!projectRootPath && !projectService.useSingleInferredProject) { _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); } - _this.enableGlobalPlugins(); + _this.enableGlobalPlugins(_this.getCompilerOptions()); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -117210,14 +119286,16 @@ var ts; var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); /*@internal*/ - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; - _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectReferences = projectReferences; + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, + /*hasExplicitListOfFiles*/ false, + /*lastFileExceededProgramSize*/ undefined, + /*compilerOptions*/ {}, + /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; /** Ref count to the project when opened from external project */ _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); - _this.enablePlugins(); return _this; } /** @@ -117225,17 +119303,24 @@ var ts; * @returns: true if set of files in the project stays the same and false - otherwise. */ ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: - return this.projectService.reloadFileNamesOfConfiguredProject(this); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; case ts.ConfigFileProgramReloadLevel.Full: this.projectService.reloadConfiguredProject(this); - return true; + result = true; + break; default: - return _super.prototype.updateGraph.call(this); + result = _super.prototype.updateGraph.call(this); } + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; }; /*@internal*/ ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { @@ -117253,11 +119338,14 @@ var ts; /*@internal*/ ConfiguredProject.prototype.getResolvedProjectReferences = function () { var program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.getResolvedProjectReferences(); }; ConfiguredProject.prototype.enablePlugins = function () { + this.enablePluginsWithOptions(this.getCompilerOptions()); + }; + /*@internal*/ + ConfiguredProject.prototype.enablePluginsWithOptions = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117277,7 +119365,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths); } } - this.enableGlobalPlugins(); + this.enableGlobalPlugins(options); }; /** * Get the errors that dont have any file name associated @@ -117355,6 +119443,10 @@ var ts; // The project is referenced only if open files impacted by this project are present in this project return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; + /*@internal*/ + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; @@ -117385,6 +119477,12 @@ var ts; _this.excludedFiles = []; return _this; } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; @@ -117412,6 +119510,7 @@ var ts; server.maxFileSize = 4 * 1024 * 1024; // tslint:disable variable-name server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.SurveyReady = "surveyReady"; server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -117522,6 +119621,12 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; + /*@internal*/ + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -117565,6 +119670,7 @@ var ts; WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { @@ -117582,11 +119688,19 @@ var ts; function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } /*@internal*/ function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } var ProjectService = /** @class */ (function () { function ProjectService(opts) { var _this = this; @@ -117594,6 +119708,7 @@ var ts; * Container of all known scripts */ this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -117644,6 +119759,8 @@ var ts; this.pendingProjectUpdates = ts.createMap(); /** Tracks projects that we have already sent telemetry for. */ this.seenProjects = ts.createMap(); + /** Tracks projects that we have already sent survey events for. */ + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117656,7 +119773,7 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); if (this.host.realpath) { @@ -117819,6 +119936,13 @@ var ts; this.eventHandler(event); }; /* @internal */ + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; + /* @internal */ ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { if (!this.eventHandler) { return; @@ -118086,7 +120210,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_27 = function (inferredProject) { + var _loop_25 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -118107,7 +120231,7 @@ var ts; // Note that we need to create a copy of the array since the list of project can change for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_27(inferredProject); + _loop_25(inferredProject); } } return project; @@ -118482,35 +120606,6 @@ var ts; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 - var result = ts.parseJsonText(configFilename, configFileContent); - if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; - } - var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), - /*existingOptions*/ {}, configFilename, - /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); - if (parsedCommandLine.errors.length) { - errors.push.apply(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, - configHasFilesProperty: parsedCommandLine.raw.files !== undefined, - configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, - wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), - typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave, - projectReferences: parsedCommandLine.projectReferences - }; - return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; - }; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { @@ -118523,12 +120618,12 @@ var ts; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var f = fileNames_2[_i]; var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { + if (ts.hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // Keep the size as zero since it's disabled return fileName; } @@ -118540,9 +120635,9 @@ var ts; return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); } function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .filter(function (name) { return hasTSFileExtension(name); }) .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); @@ -118553,21 +120648,37 @@ var ts; var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(projectFileName, project); return project; }; - ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { - if (this.seenProjects.has(projectKey)) { + /*@internal*/ + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { + return; + } + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + /*@internal*/ + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); return; } - this.seenProjects.set(projectKey, true); + this.seenProjects.set(project.projectName, true); if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); return; } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); var data = { - projectId: this.host.createSHA256Hash(projectKey), + projectId: this.host.createSHA256Hash(project.projectName), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -118586,8 +120697,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; // TODO: GH#18217 - return server.getBaseConfigFileName(configFilePath) || "other"; + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -118598,34 +120708,85 @@ var ts; }; } }; - ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); - // This doesnt need scheduling since its either creation or reload of the project - project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 - var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, // TODO: GH#18217 - lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); - project.configFileSpecs = configFileSpecs; + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); // TODO: We probably should also watch the configFiles that are extended project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); - if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 - } - project.setProjectErrors(configFileErrors); - var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); // TODO: GH#18217 this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); - this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; + /* @internal */ + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + return project; + }; + /* @internal */ + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project); + return project; + }; + /* @internal */ + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName) { + var project = this.createAndLoadConfiguredProject(configFileName); + project.updateGraph(); + return project; + }; + /** + * Read the config file of the project, and update the project root file names. + */ + /* @internal */ + ProjectService.prototype.loadConfiguredProject = function (project) { + // Read updated contents from disk + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + // Update the project + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217 + } + project.enablePluginsWithOptions(compilerOptions); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); // TODO: GH#18217 + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); @@ -118681,14 +120842,14 @@ var ts; // mark the project as dirty unconditionally project.markAsDirty(); }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently // therefore if it is undefined, it should not be updated. if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; /** * Reload the file names from config file specs and update the project graph @@ -118699,11 +120860,11 @@ var ts; var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); - this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; /** - * Read the config file of the project again and update the project + * Read the config file of the project again by clearing the cache and update the project graph */ /* @internal */ ProjectService.prototype.reloadConfiguredProject = function (project) { @@ -118713,22 +120874,9 @@ var ts; host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); - // Read updated contents from disk - var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; - // Update the project - project.configFileSpecs = configFileSpecs; - project.setProjectErrors(configFileErrors); - project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - } - else { - project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 - } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); // TODO: GH#18217 + // Load project from the disk + this.loadConfiguredProject(project); + project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -118853,7 +121001,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_28 = function (project) { + var _loop_26 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -118870,7 +121018,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_28(project); + _loop_26(project); } } } @@ -118883,10 +121031,80 @@ var ts; if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } } }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + // Watch only directory + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + // Has extension + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + // Folder + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1 /* Recursive */, "node_modules for closed script infos in them" /* NodeModulesForClosedScriptInfo */); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -118952,6 +121170,7 @@ var ts; return this.filenameToScriptInfo.get(fileName); }; ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { @@ -118969,7 +121188,19 @@ var ts; this.logger.info("Format host information updated"); } if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + // Load configured projects for external projects that are pending reload + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + _this.loadConfiguredProject(project); + project.updateGraph(); + } + }); + } } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; @@ -119030,17 +121261,14 @@ var ts; // otherwise we create a new one. var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { - var project = _this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - _this.createConfiguredProject(configFileName); - updatedProjects.set(configFileName, true); - } - else if (!updatedProjects.has(configFileName)) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; _this.delayUpdateProjectGraph(project); } else { + // reload from the disk _this.reloadConfiguredProject(project); } updatedProjects.set(configFileName, true); @@ -119121,7 +121349,7 @@ var ts; var configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createAndLoadConfiguredProject(configFileName); updateProjectIfDirty(configuredProject); // Keep this configured project as referenced from project addOriginalConfiguredProject(configuredProject); @@ -119165,7 +121393,7 @@ var ts; if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName); // Send the event only if the project got created as part of this open request and info is part of the project if (info.isOrphan()) { // Since the file isnt part of configured project, do not send config file info @@ -119276,13 +121504,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_29 = function (proj) { + var _loop_27 = function (proj) { var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_29(proj); + _loop_27(proj); } }; /* @internal */ @@ -119392,7 +121620,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_30 = function (name) { + var _loop_28 = function (name) { var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -119410,7 +121638,7 @@ var ts; } } if (rule.exclude) { - var _loop_32 = function (exclude) { + var _loop_30 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -119437,7 +121665,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_32(exclude); + _loop_30(exclude); } } else { @@ -119453,11 +121681,11 @@ var ts; var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_30(name); + _loop_28(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_31 = function (i) { + var _loop_29 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -119495,7 +121723,7 @@ var ts; }; var this_4 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_31(i); + _loop_29(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -119546,7 +121774,9 @@ var ts; externalProject.enableLanguageService(); } // external project already exists and not config files were added - update the project and return; - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + // The graph update here isnt postponed since any file open operation needs all updated external projects + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); return; } // some config files were added to external project (that previously were not there) @@ -119594,8 +121824,10 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - // errors are stored in the project - project = this.createConfiguredProject(tsconfigFile); + // errors are stored in the project, do not need to update the graph + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project @@ -119605,8 +121837,11 @@ var ts; } else { // no config files - remove the item from the collection + // Create external project and update its graph, do not delay update since + // any file open operation needs all updated external projects this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); } }; ProjectService.prototype.hasDeferredExtension = function () { @@ -119822,7 +122057,7 @@ var ts; /** * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. */ - function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + function combineProjectOutput(defaultValue, getValue, projects, action) { var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { @@ -119830,9 +122065,7 @@ var ts; outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); }); } - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); + return ts.deduplicate(outputs, ts.equateValues); } function combineProjectOutputFromEveryProject(projectService, action, areEqual) { var outputs = []; @@ -119877,24 +122110,27 @@ var ts; } function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; - var _loop_33 = function (outputReferencedSymbol) { - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + var _loop_31 = function (outputReferencedSymbol) { + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition: definition, references: [] }; outputs.push(symbolToAddTo); } for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { var ref = _a[_i]; - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } }; for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.position) || server.emptyArray; _i < _b.length; _i++) { var outputReferencedSymbol = _b[_i]; - _loop_33(outputReferencedSymbol); + _loop_31(outputReferencedSymbol); } }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); return outputs.filter(function (o) { return o.references.length !== 0; }); @@ -119950,7 +122186,7 @@ var ts; seenProjects.set(projectAndLocation.project.projectName, true); var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); if (!originalLocation) - return false; + return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { @@ -119966,7 +122202,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -120353,6 +122589,10 @@ var ts; diagnostics: bakedDiags }, "configFileDiag"); break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, "surveyReady"); + break; case server.ProjectLanguageServiceStateEvent: { var eventName = "projectLanguageServiceState"; this.event({ @@ -120852,13 +123092,12 @@ var ts; if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; - // strips 'triggerSpan' - Session.mapRenameInfo = function (_a) { - var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; - return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + Session.prototype.mapRenameInfo = function (_a, scriptInfo) { + var canRename = _a.canRename, fileToRename = _a.fileToRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers, triggerSpan = _a.triggerSpan; + return { canRename: canRename, fileToRename: fileToRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }; }; Session.prototype.toSpanGroups = function (locations) { var map = ts.createMap(); @@ -121099,7 +123338,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (completions === undefined) return undefined; if (kind === "completions-full" /* CompletionsFull */) @@ -121441,8 +123680,8 @@ var ts; var commands = args.command; // They should be sending back the command we sent them. for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - var project = this.getFileAndProject(command).project; - project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); } return {}; }; @@ -121686,8 +123925,8 @@ var ts; continue; } for (var i = textChanges_4.length - 1; i >= 0; i--) { - var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_7); + var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); } } return text; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 096362cc6a767..4b01738783d9c 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -536,6 +536,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +633,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +670,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1808,7 +1811,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2060,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2581,7 +2585,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2595,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2693,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2993,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3211,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4183,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4316,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4385,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4394,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4430,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4441,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4454,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4662,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4720,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4884,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5268,6 +5113,11 @@ declare namespace ts { } interface RenameInfo { canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; localizedErrorMessage?: string; displayName: string; fullDisplayName: string; diff --git a/lib/typescript.js b/lib/typescript.js index 78365f95075b7..59b477e1b7ef6 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -75,7 +75,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -88,6 +88,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +717,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +778,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1155,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1275,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1935,6 +1946,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2044,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2734,38 +3109,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2993,9 +3368,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3388,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3796,17 +4170,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4742,7 +5120,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5159,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5406,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5433,13 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5531,8 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + Index_0_is_out_of_bounds_in_tuple_of_length_1: diag(2733, ts.DiagnosticCategory.Error, "Index_0_is_out_of_bounds_in_tuple_of_length_1_2733", "Index '{0}' is out-of-bounds in tuple of length {1}."), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5646,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5742,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5840,14 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5878,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5945,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,6 +6074,8 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; @@ -6394,6 +6797,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6827,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6878,6 +7283,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7322,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7397,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7555,6 +7984,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +8007,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8088,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8195,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8425,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8465,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8840,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -9135,18 +9571,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9622,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9652,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9672,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9700,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9714,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9748,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9792,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9807,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9838,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9847,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9957,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +9999,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10193,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10223,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10311,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10320,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10614,7 +11068,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11189,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11205,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11107,10 +11561,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11703,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11815,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +11992,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +12005,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12258,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12585,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12603,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12611,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12643,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12689,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12717,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12860,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14219,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14612,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14640,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14653,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14933,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15154,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14910,31 +15447,36 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; @@ -15067,14 +15609,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15787,10 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15879,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15950,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16309,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16478,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -17367,8 +17919,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +20018,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -21061,7 +21616,7 @@ var ts; nextJSDocToken(); } } - function skipWhitespaceOrAsterisk() { + function skipWhitespaceOrAsterisk(next) { if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range @@ -21075,7 +21630,7 @@ var ts; else if (token() === 39 /* AsteriskToken */) { precedingLineBreak = false; } - nextJSDocToken(); + next(); } } function parseTag(indent) { @@ -21083,8 +21638,9 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespaceOrAsterisk(); + // Use 'nextToken' instead of 'nextJsDocToken' so we can parse a type like 'number' in `@enum number` + var tagName = parseJSDocIdentifierName(/*message*/ undefined, nextToken); + skipWhitespaceOrAsterisk(nextToken); var tag; switch (tagName.escapedText) { case "augments": @@ -21221,7 +21777,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21255,7 +21811,7 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { @@ -21264,10 +21820,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21835,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21930,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(nextJSDocToken); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21945,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +22006,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22046,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22084,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22110,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -21611,7 +22163,8 @@ var ts; } return entity; } - function parseJSDocIdentifierName(message) { + function parseJSDocIdentifierName(message, next) { + if (next === void 0) { next = nextJSDocToken; } if (!ts.tokenIsIdentifierOrKeyword(token())) { return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } @@ -21620,7 +22173,7 @@ var ts; var result = createNode(71 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); - nextJSDocToken(); + next(); return result; } } @@ -22399,8 +22952,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22966,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23049,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23063,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23083,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23096,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23104,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23122,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23232,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23241,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,6 +23250,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22677,6 +23259,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23268,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23277,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23311,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23324,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23332,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23342,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23358,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23370,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23381,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23466,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23530,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23550,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23596,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23604,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23632,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23660,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23751,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23801,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23821,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23829,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23865,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23908,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23933,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23926,7 +24582,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24600,21 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + if (filesSpecs.length === 0 && hasZeroOrNoReferences) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23985,14 +24655,13 @@ var ts; } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24669,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24110,11 +24778,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24824,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24832,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25046,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24446,12 +25109,8 @@ var ts; } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25299,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25321,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25330,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); } - return; } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); } - return path; + return; } + return result; } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25461,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25482,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25508,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25528,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,11 +25567,11 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { // Return just the type directive names result.push(ts.getBaseFileName(normalized)); @@ -25086,15 +25797,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25843,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25862,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25873,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25938,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25947,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +25961,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +25978,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26009,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26050,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26103,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26122,41 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); - } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state); if (fromPackageJson) { return fromPackageJson; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(candidate, state.host); + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26168,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,23 +26180,24 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); + function loadModuleFromPackageJson(jsonContent, versionPaths, extensions, candidate, state) { + var file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) + : readPackageJsonMainField(jsonContent, candidate, state); if (!file) { if (extensions === Extensions.TypeScript) { // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + file = readPackageJsonMainField(jsonContent, candidate, state); if (!file) { return undefined; } @@ -25511,26 +26206,35 @@ var ts; return undefined; } } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailures = !ts.directoryProbablyExists(ts.getDirectoryPath(file), state.host); + if (versionPaths && ts.containsPath(candidate, file)) { + var moduleName = ts.getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state)); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26254,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26384,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26397,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26442,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26474,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26691,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26746,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26826,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26905,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26419,6 +27171,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -27217,7 +27971,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +27991,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28079,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28098,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28323,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28370,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28387,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28468,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28492,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28503,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,14 +28586,18 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { @@ -27901,7 +28656,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28686,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28743,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28764,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28790,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28831,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28844,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28928,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28944,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28964,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +28982,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29023,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29035,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29061,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29099,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28382,6 +29137,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -29434,6 +30192,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30224,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29670,8 +30441,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30510,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30541,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29933,6 +30718,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30762,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30898,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30959,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +30972,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30224,12 +31013,12 @@ var ts; var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); @@ -30246,7 +31035,7 @@ var ts; } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); }); } @@ -30360,8 +31149,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31293,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,7 +31302,7 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + if (meaning & 67220415 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { // parameters are visible only inside function body, parameter list and return type // technically for parameter list case here we might mix parameters and variables declared in function, // however it is detected separately when checking initializers of parameters @@ -30599,7 +31388,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31398,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31428,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31448,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30739,7 +31531,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31586,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31689,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31710,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30968,6 +31763,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31835,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31889,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31181,7 +31979,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +31998,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32013,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32047,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,7 +32096,7 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -31311,11 +32109,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32129,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32164,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32180,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32202,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32238,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32257,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32289,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32297,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,18 +32309,17 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; @@ -31737,7 +32553,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32653,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32703,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32771,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32813,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32931,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32941,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32262,13 +33091,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33117,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,14 +33184,14 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; @@ -32435,23 +33264,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33362,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33402,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33415,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33513,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33647,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33658,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33699,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,6 +33711,16 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. @@ -32996,7 +33833,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33848,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33161,7 +34005,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34189,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34213,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34262,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33670,7 +34516,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34547,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34582,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34605,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34614,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34624,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33790,8 +34642,8 @@ var ts; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34662,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34676,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33876,8 +34728,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34737,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -34037,7 +34889,14 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { return checkExpression(declaration.expression); @@ -34047,9 +34906,9 @@ var ts; return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34922,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +34983,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34182,7 +35041,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35069,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35078,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35107,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35116,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,15 +35282,15 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { + var isJavascript = ts.isInJSFile(location); + if (isJSConstructorType(type) && !typeArgCount) { return getSignaturesOfType(type, 0 /* Call */); } return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); @@ -34447,7 +35298,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34529,8 +35380,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35480,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35619,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35847,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35867,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36121,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35765,10 +36616,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36641,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36721,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36729,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36762,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36778,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36788,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36837,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36858,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36192,7 +37072,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37172,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37185,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37222,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37253,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37340,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36537,7 +37417,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37436,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37482,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,7 +37676,7 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; @@ -36825,7 +37709,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37764,28 @@ var ts; if (type) { return type; } + // JS are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37793,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36911,10 +37809,6 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); - } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -37029,10 +37923,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -37087,10 +37981,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37144,7 +38038,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37333,10 +38227,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38242,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38287,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38315,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38412,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38421,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38676,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,7 +38689,7 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; @@ -37869,7 +38748,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38766,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38777,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38790,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38828,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38856,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39055,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39085,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39099,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39241,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39252,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39458,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39559,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39569,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39628,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39649,24 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); - } + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38858,49 +39729,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } - } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39861,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39049,33 +39936,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40036,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40053,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40067,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40110,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40143,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40199,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40230,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40256,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40286,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40456,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40594,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40653,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40755,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40765,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39850,7 +40782,7 @@ var ts; return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39895,6 +40827,9 @@ var ts; } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40858,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,6 +40886,14 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -40140,6 +41084,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41143,24 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K] + if (relation !== identityRelation) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41178,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41250,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41303,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41345,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41479,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41510,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41703,33 @@ var ts; return false; } } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42018,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41107,10 +42095,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42123,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42145,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42159,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41457,19 +42450,23 @@ var ts; function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) : + sourceRestType ? targetCount : + Math.min(sourceCount, targetCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41784,6 +42781,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42819,14 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +42922,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); - } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +42963,15 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43002,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43026,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43044,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43057,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43070,17 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { - if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & 32768 /* Never */)) { + // If we have contravariant inferences, but no covariant inferences or a single + // covariant inference of 'never', we find the best common subtype and treat that + // as a single covariant candidate. + inference.candidates = [getContravariantInference(inference)]; inference.contraCandidates = undefined; } if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + inferredType = getCovariantInference(inference, signature); } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43097,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43126,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42289,6 +43333,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43353,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43369,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43407,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42476,10 +43541,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43590,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42567,8 +43649,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43730,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43811,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +43915,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +43928,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +43959,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42914,6 +44005,9 @@ var ts; else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44266,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44292,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44312,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43436,7 +44613,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43509,7 +44686,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43768,31 +44945,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +44982,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -44039,7 +45241,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45298,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44212,7 +45414,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45435,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45458,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45478,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); - } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44500,7 +45736,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45755,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45769,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +45841,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +45951,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +45988,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46010,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46019,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44815,6 +46057,9 @@ var ts; } return createTupleType(elementTypes, minLength, hasRestElement); } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } @@ -44907,9 +46152,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46172,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46382,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46406,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46414,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46423,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45198,7 +46445,7 @@ var ts; createArrayType(getUnionType(childrenTypes)); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46462,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46495,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46543,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46553,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46620,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46644,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +46866,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +46982,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47103,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47151,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47306,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47425,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47530,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47596,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47604,14 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + if (isTupleType(objectType) && !objectType.target.hasRestElement && ts.isNumericLiteral(indexExpression)) { + var index = +indexExpression.text; + var maximumIndex = ts.length(objectType.target.typeParameters); + if (index >= maximumIndex) { + error(indexExpression, ts.Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); + } + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47732,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47756,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47767,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47802,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47811,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +47869,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +47910,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +47921,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +47992,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48026,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48047,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; - } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); - } - } - else { - return args.length; - } - } - /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. - */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. - */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; + return getEffectiveDecoratorArguments(node); } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; + return args; } /** - * Gets the effective argument expression for an argument in a call expression. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - return args[argIndex]; + return ts.Debug.fail(); } /** - * Gets the error node to use when reporting errors for an effective argument. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48136,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48145,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48159,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48210,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48293,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48323,74 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } - } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; - } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47414,17 +48460,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47497,12 +48553,19 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48638,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48714,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47745,7 +48811,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,8 +48890,8 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (node && ts.isInJSFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; @@ -47837,21 +48903,21 @@ var ts; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +48930,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +48987,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +48998,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49008,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49035,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49094,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49219,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49232,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,21 +49256,23 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { + function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } + return !isTupleType(restType) || restType.target.hasRestElement; } - return undefined; + return false; } - function hasEffectiveRestParameter(signature) { + function getEffectiveRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - return !isTupleType(restType) || restType.target.hasRestElement; + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } - return false; + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -48424,10 +49476,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49580,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48556,8 +49659,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48803,8 +49908,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -49105,7 +50210,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50348,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50365,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50426,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50436,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50542,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,9 +50584,9 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { if (noImplicitAny) { reportImplicitAnyError(declaration, anyType); @@ -49522,11 +50627,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50678,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50704,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50721,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50746,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50777,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +50870,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +50899,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51365,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51396,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50627,6 +51737,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51801,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +51830,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52063,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52086,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52143,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51302,7 +52412,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +52898,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +52981,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53021,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53037,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52888,7 +53998,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -53114,6 +54224,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54715,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54727,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54780,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +54841,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +54878,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +54910,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +54958,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55125,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54260,7 +55372,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55457,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55487,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55513,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55525,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55551,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55570,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55584,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55601,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55680,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55696,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55706,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,7 +55714,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { @@ -54611,9 +55724,7 @@ var ts; if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType); } return typeFromTypeNode; } @@ -54623,8 +55734,7 @@ var ts; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var classType = getTypeOfClassContainingHeritageClause(node); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54658,6 +55768,9 @@ var ts; } return errorType; } + function getTypeOfClassContainingHeritageClause(node) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent)); + } // Gets the type of object literal or array literal of destructuring assignment. // { a } from // for ( { a } of elems) { @@ -54719,6 +55832,22 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { @@ -54786,13 +55915,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +55970,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,7 +55983,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -54950,7 +56079,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56092,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56137,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56200,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56304,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56319,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56375,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55280,9 +56432,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56523,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55478,7 +56633,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57007,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57210,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57256,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57476,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57575,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57740,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57775,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61352,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61380,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -69197,19 +70391,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. if (node.transformFlags & 8388608 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -73516,7 +74718,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 67108864 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +74775,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +74806,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -76808,11 +78016,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78046,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78064,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78074,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78146,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,6 +78167,7 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76974,6 +78185,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78204,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78217,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77046,13 +78262,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78283,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +78808,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77865,10 +79110,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79111,7 +80357,7 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; @@ -79136,7 +80382,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79229,12 +80475,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81209,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81231,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +81656,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +81867,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +82572,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +82604,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +82778,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83200,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83391,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +83470,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +83984,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84017,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84027,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84035,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84047,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84059,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84075,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84109,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84136,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84224,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84240,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84302,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84311,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84335,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84362,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83196,7 +84470,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +84482,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +84574,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +84610,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +84655,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +84746,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +84758,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +84789,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +84810,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +84841,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +84868,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +84938,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +84954,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +84990,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85015,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85030,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85093,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85159,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85250,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +85479,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84371,6 +85662,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84457,6 +85749,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +85779,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +85808,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +85895,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +85904,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +85924,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +85944,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +85964,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +85975,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86024,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86037,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86096,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84863,9 +86144,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86161,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86360,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86377,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86388,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +86465,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +86475,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +86504,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,7 +86515,7 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } @@ -85752,7 +87039,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87052,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87233,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87391,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86575,121 +87869,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); - } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88043,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88060,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88081,27 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +88110,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86923,13 +88204,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88272,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88280,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88330,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88346,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88380,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88411,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +88425,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +88477,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,7 +88512,7 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; @@ -87273,7 +88585,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +88624,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +88651,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87550,6 +88863,7 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -87637,6 +88951,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +88973,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +88991,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } - } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); - } - } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); - } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; + return lookup.get(toPath(fileName)); } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; + function getSize() { + return lookup.size; } - function getKeys() { - return allKeys.getKeys(); + function clear() { + lookup.clear(); } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89062,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89077,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,386 +89098,598 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } + watchWildCardDirectories(resolved, cfg); // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } + watchInputFiles(resolved, cfg); } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); } } - function resetBuildContext(opts) { - if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); - } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + if (result.fileNames.length !== 0) { + ts.filterMutate(proj.errors, function (error) { return !ts.isErrorNoInputFiles(error); }); + } + else if (!proj.configFileSpecs.filesSpecs && !ts.some(proj.errors, ts.isErrorNoInputFiles)) { + proj.errors.push(ts.getErrorForNoInputFiles(proj.configFileSpecs, resolved)); + } + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { @@ -88190,420 +89698,221 @@ var ts; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; - } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +89948,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +89960,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90103,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90148,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90224,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90309,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90347,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +90438,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +90487,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +90726,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +90785,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +90907,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91044,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91408,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +91426,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +91435,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +91663,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +91777,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +91785,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90883,7 +92296,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92304,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -91273,7 +92686,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +92695,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +93453,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_9 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_9(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +93502,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +93519,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_10 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_10(moduleName); } } if (!foundGlobal) { @@ -92202,7 +93636,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +93669,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +93693,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +93812,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92471,7 +93918,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +93926,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +93954,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94026,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94114,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94127,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94154,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94172,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94199,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +94612,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +94637,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +94646,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +94784,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +94799,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +94836,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +94864,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +94888,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +94909,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +94939,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +94963,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + resolvedModuleSymbol.declarations.some(function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95205,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95240,16 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; } } return undefined; @@ -93928,10 +95403,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +95415,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -94151,17 +95625,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +95660,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +95732,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94748,9 +96224,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96268,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96282,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96349,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +96637,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +96668,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +96788,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,6 +96933,14 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); function nodeEntry(node, isInString) { return { type: "node", node: node.name || node, isInString: isInString }; } @@ -95490,9 +96974,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95521,28 +97005,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95571,7 +97055,7 @@ var ts; textSpan: getTextSpan(node, sourceFile), isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString, }; @@ -95635,7 +97119,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95725,7 +97264,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95894,7 +97433,7 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; @@ -96062,8 +97601,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +97651,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +97709,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +97736,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96602,7 +98141,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98199,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96673,7 +98213,7 @@ var ts; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } @@ -96777,8 +98317,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +98380,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +98483,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_11 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +98511,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_11(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +98541,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +98571,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +98613,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +98879,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99099,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99132,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99195,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99255,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99298,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_12 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99308,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_12(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99323,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +99647,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -99248,13 +100805,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_13 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_13(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +101351,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,9 +101362,34 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + localizedErrorMessage: undefined, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, localizedErrorMessage: undefined, @@ -99882,17 +101464,26 @@ var ts; return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +101492,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +101523,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +101545,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100239,7 +101834,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + var _loop_14 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100249,7 +101844,7 @@ var ts; } }; for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + var state_4 = _loop_14(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +101859,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +101876,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +101951,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102075,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102104,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100539,7 +102154,7 @@ var ts; var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102179,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102192,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102211,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +102382,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +102529,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +102759,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +102831,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +102899,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +102973,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_15 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +102992,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_15(opt); } return options; } @@ -104156,7 +105799,7 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } @@ -104194,7 +105837,7 @@ var ts; this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104262,24 +105905,31 @@ var ts; }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +105952,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106077,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106109,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106117,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_16 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106152,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_16(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106191,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106209,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_17 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_17(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106226,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); - return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + return applyChanges(nonFormattedText, changes); } - changesToText.newFileChanges = newFileChanges; + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,7 +106275,7 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } })(changesToText || (changesToText = {})); @@ -105399,7 +107060,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,30 +107113,41 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } @@ -105485,24 +107157,19 @@ var ts; var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_18 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_18(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107216,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107230,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107244,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107270,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107293,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107303,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || []).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { return []; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,6 +107337,7 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } + codeActionSucceeded = false; return []; } function transformCatch(node, transformer, prevArgName) { @@ -105670,17 +107353,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +107380,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +107396,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +107409,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return ts.createNodeArray([ts.createStatement(rightHandSide)]); + } if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); } return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; - var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + } + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, argName ? [argName.identifier] : []); if (shouldReturn) { return ts.createNodeArray([ts.createReturn(synthCall)]); } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105775,47 +107478,59 @@ var ts; } } return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return ts.createNodeArray(innerCbBody); } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + if (!shouldReturn) { + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } return ts.createNodeArray([]); } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } return ts.createNodeArray(ret); } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { @@ -105837,12 +107552,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +107559,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +107648,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +107765,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108251,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); } } }); return result; } function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + return !(s.flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +108345,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +108404,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106742,13 +108456,9 @@ var ts; } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +108468,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && { symbol: symbol, symbolForMeaning: info.symbolForMeaning, name: info.name, kind: kind }; + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +108491,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +108734,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +108776,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +108805,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_19 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +108832,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_19(info); } }); })); @@ -107151,7 +108876,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +108886,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109006,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109018,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +109882,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110014,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110036,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108301,7 +110135,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return undefined; // TODO: GH#20113 } var token = ts.getTokenAtPosition(sourceFile, start); @@ -108750,16 +110584,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +110611,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +110841,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +110867,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +111517,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_20 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +111536,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_20(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112162,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +112378,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +112712,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +112768,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_21 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +112808,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_21(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113082,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111322,10 +113358,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_22 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_23 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +113383,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_23(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_22(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +113806,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +114380,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +114559,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +114901,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +114940,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +114965,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115080,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115123,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113389,19 +115430,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 887e98b6f5d90..f664d17bfcb13 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -536,6 +536,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +633,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +670,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1808,7 +1811,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2060,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2581,7 +2585,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2595,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2693,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2993,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3211,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4183,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4316,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4385,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4394,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4430,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4441,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4454,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4662,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4720,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4884,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5268,6 +5113,11 @@ declare namespace ts { } interface RenameInfo { canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; localizedErrorMessage?: string; displayName: string; fullDisplayName: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 78365f95075b7..59b477e1b7ef6 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -75,7 +75,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -88,6 +88,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +717,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +778,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1155,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1275,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1935,6 +1946,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2044,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2734,38 +3109,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2993,9 +3368,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3388,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3796,17 +4170,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4742,7 +5120,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5159,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5406,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5433,13 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5531,8 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + Index_0_is_out_of_bounds_in_tuple_of_length_1: diag(2733, ts.DiagnosticCategory.Error, "Index_0_is_out_of_bounds_in_tuple_of_length_1_2733", "Index '{0}' is out-of-bounds in tuple of length {1}."), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5646,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5742,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5840,14 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5878,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5945,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,6 +6074,8 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; @@ -6394,6 +6797,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6827,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6878,6 +7283,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7322,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7397,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7555,6 +7984,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +8007,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8088,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8195,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8425,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8465,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8840,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -9135,18 +9571,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9622,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9652,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9672,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9700,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9714,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9748,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9792,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9807,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9838,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9847,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9957,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +9999,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10193,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10223,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10311,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10320,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10614,7 +11068,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11189,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11205,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11107,10 +11561,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11703,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11815,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +11992,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +12005,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12258,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12585,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12603,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12611,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12643,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12689,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12717,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12860,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14219,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14612,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14640,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14653,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14933,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15154,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14910,31 +15447,36 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; @@ -15067,14 +15609,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15787,10 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15879,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15950,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16309,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16478,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -17367,8 +17919,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +20018,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -21061,7 +21616,7 @@ var ts; nextJSDocToken(); } } - function skipWhitespaceOrAsterisk() { + function skipWhitespaceOrAsterisk(next) { if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range @@ -21075,7 +21630,7 @@ var ts; else if (token() === 39 /* AsteriskToken */) { precedingLineBreak = false; } - nextJSDocToken(); + next(); } } function parseTag(indent) { @@ -21083,8 +21638,9 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespaceOrAsterisk(); + // Use 'nextToken' instead of 'nextJsDocToken' so we can parse a type like 'number' in `@enum number` + var tagName = parseJSDocIdentifierName(/*message*/ undefined, nextToken); + skipWhitespaceOrAsterisk(nextToken); var tag; switch (tagName.escapedText) { case "augments": @@ -21221,7 +21777,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21255,7 +21811,7 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { @@ -21264,10 +21820,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21835,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21930,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(nextJSDocToken); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21945,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +22006,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22046,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22084,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22110,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -21611,7 +22163,8 @@ var ts; } return entity; } - function parseJSDocIdentifierName(message) { + function parseJSDocIdentifierName(message, next) { + if (next === void 0) { next = nextJSDocToken; } if (!ts.tokenIsIdentifierOrKeyword(token())) { return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } @@ -21620,7 +22173,7 @@ var ts; var result = createNode(71 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); - nextJSDocToken(); + next(); return result; } } @@ -22399,8 +22952,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22966,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23049,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23063,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23083,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23096,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23104,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23122,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23232,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23241,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,6 +23250,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22677,6 +23259,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23268,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23277,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23311,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23324,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23332,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23342,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23358,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23370,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23381,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23466,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23530,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23550,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23596,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23604,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23632,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23660,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23751,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23801,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23821,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23829,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23865,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23908,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23933,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23926,7 +24582,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24600,21 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + if (filesSpecs.length === 0 && hasZeroOrNoReferences) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23985,14 +24655,13 @@ var ts; } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24669,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24110,11 +24778,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24824,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24832,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25046,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24446,12 +25109,8 @@ var ts; } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25299,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25321,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25330,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); } - return; } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); } - return path; + return; } + return result; } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25461,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25482,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25508,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25528,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,11 +25567,11 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { // Return just the type directive names result.push(ts.getBaseFileName(normalized)); @@ -25086,15 +25797,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25843,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25862,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25873,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25938,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25947,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +25961,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +25978,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26009,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26050,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26103,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26122,41 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); - } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state); if (fromPackageJson) { return fromPackageJson; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(candidate, state.host); + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26168,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,23 +26180,24 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); + function loadModuleFromPackageJson(jsonContent, versionPaths, extensions, candidate, state) { + var file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) + : readPackageJsonMainField(jsonContent, candidate, state); if (!file) { if (extensions === Extensions.TypeScript) { // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + file = readPackageJsonMainField(jsonContent, candidate, state); if (!file) { return undefined; } @@ -25511,26 +26206,35 @@ var ts; return undefined; } } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailures = !ts.directoryProbablyExists(ts.getDirectoryPath(file), state.host); + if (versionPaths && ts.containsPath(candidate, file)) { + var moduleName = ts.getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state)); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26254,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26384,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26397,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26442,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26474,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26691,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26746,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26826,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26905,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26419,6 +27171,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -27217,7 +27971,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +27991,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28079,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28098,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28323,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28370,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28387,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28468,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28492,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28503,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,14 +28586,18 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { @@ -27901,7 +28656,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28686,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28743,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28764,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28790,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28831,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28844,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28928,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28944,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28964,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +28982,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29023,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29035,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29061,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29099,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28382,6 +29137,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -29434,6 +30192,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30224,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29670,8 +30441,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30510,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30541,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29933,6 +30718,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30762,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30898,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30959,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +30972,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30224,12 +31013,12 @@ var ts; var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); @@ -30246,7 +31035,7 @@ var ts; } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); }); } @@ -30360,8 +31149,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31293,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,7 +31302,7 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + if (meaning & 67220415 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { // parameters are visible only inside function body, parameter list and return type // technically for parameter list case here we might mix parameters and variables declared in function, // however it is detected separately when checking initializers of parameters @@ -30599,7 +31388,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31398,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31428,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31448,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30739,7 +31531,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31586,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31689,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31710,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30968,6 +31763,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31835,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31889,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31181,7 +31979,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +31998,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32013,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32047,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,7 +32096,7 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -31311,11 +32109,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32129,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32164,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32180,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32202,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32238,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32257,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32289,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32297,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,18 +32309,17 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; @@ -31737,7 +32553,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32653,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32703,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32771,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32813,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32931,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32941,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32262,13 +33091,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33117,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,14 +33184,14 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; @@ -32435,23 +33264,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33362,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33402,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33415,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33513,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33647,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33658,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33699,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,6 +33711,16 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. @@ -32996,7 +33833,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33848,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33161,7 +34005,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34189,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34213,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34262,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33670,7 +34516,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34547,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34582,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34605,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34614,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34624,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33790,8 +34642,8 @@ var ts; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34662,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34676,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33876,8 +34728,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34737,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -34037,7 +34889,14 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { return checkExpression(declaration.expression); @@ -34047,9 +34906,9 @@ var ts; return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34922,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +34983,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34182,7 +35041,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35069,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35078,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35107,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35116,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,15 +35282,15 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { + var isJavascript = ts.isInJSFile(location); + if (isJSConstructorType(type) && !typeArgCount) { return getSignaturesOfType(type, 0 /* Call */); } return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); @@ -34447,7 +35298,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34529,8 +35380,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35480,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35619,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35847,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35867,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36121,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35765,10 +36616,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36641,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36721,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36729,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36762,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36778,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36788,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36837,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36858,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36192,7 +37072,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37172,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37185,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37222,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37253,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37340,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36537,7 +37417,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37436,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37482,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,7 +37676,7 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; @@ -36825,7 +37709,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37764,28 @@ var ts; if (type) { return type; } + // JS are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37793,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36911,10 +37809,6 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); - } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -37029,10 +37923,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -37087,10 +37981,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37144,7 +38038,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37333,10 +38227,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38242,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38287,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38315,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38412,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38421,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38676,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,7 +38689,7 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; @@ -37869,7 +38748,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38766,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38777,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38790,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38828,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38856,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39055,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39085,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39099,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39241,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39252,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39458,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39559,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39569,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39628,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39649,24 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); - } + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38858,49 +39729,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } - } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39861,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39049,33 +39936,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40036,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40053,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40067,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40110,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40143,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40199,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40230,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40256,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40286,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40456,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40594,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40653,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40755,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40765,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39850,7 +40782,7 @@ var ts; return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39895,6 +40827,9 @@ var ts; } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40858,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,6 +40886,14 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -40140,6 +41084,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41143,24 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K] + if (relation !== identityRelation) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41178,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41250,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41303,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41345,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41479,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41510,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41703,33 @@ var ts; return false; } } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42018,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41107,10 +42095,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42123,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42145,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42159,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41457,19 +42450,23 @@ var ts; function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) : + sourceRestType ? targetCount : + Math.min(sourceCount, targetCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41784,6 +42781,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42819,14 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +42922,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); - } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +42963,15 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43002,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43026,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43044,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43057,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43070,17 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { - if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & 32768 /* Never */)) { + // If we have contravariant inferences, but no covariant inferences or a single + // covariant inference of 'never', we find the best common subtype and treat that + // as a single covariant candidate. + inference.candidates = [getContravariantInference(inference)]; inference.contraCandidates = undefined; } if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + inferredType = getCovariantInference(inference, signature); } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43097,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43126,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42289,6 +43333,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43353,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43369,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43407,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42476,10 +43541,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43590,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42567,8 +43649,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43730,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43811,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +43915,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +43928,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +43959,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42914,6 +44005,9 @@ var ts; else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44266,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44292,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44312,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43436,7 +44613,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43509,7 +44686,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43768,31 +44945,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +44982,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -44039,7 +45241,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45298,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44212,7 +45414,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45435,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45458,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45478,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); - } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44500,7 +45736,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45755,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45769,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +45841,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +45951,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +45988,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46010,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46019,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44815,6 +46057,9 @@ var ts; } return createTupleType(elementTypes, minLength, hasRestElement); } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } @@ -44907,9 +46152,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46172,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46382,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46406,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46414,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46423,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45198,7 +46445,7 @@ var ts; createArrayType(getUnionType(childrenTypes)); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46462,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46495,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46543,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46553,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46620,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46644,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +46866,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +46982,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47103,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47151,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47306,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47425,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47530,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47596,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47604,14 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + if (isTupleType(objectType) && !objectType.target.hasRestElement && ts.isNumericLiteral(indexExpression)) { + var index = +indexExpression.text; + var maximumIndex = ts.length(objectType.target.typeParameters); + if (index >= maximumIndex) { + error(indexExpression, ts.Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); + } + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47732,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47756,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47767,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47802,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47811,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +47869,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +47910,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +47921,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +47992,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48026,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48047,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; - } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); - } - } - else { - return args.length; - } - } - /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. - */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. - */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; + return getEffectiveDecoratorArguments(node); } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; + return args; } /** - * Gets the effective argument expression for an argument in a call expression. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - return args[argIndex]; + return ts.Debug.fail(); } /** - * Gets the error node to use when reporting errors for an effective argument. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48136,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48145,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48159,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48210,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48293,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48323,74 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } - } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; - } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47414,17 +48460,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47497,12 +48553,19 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48638,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48714,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47745,7 +48811,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,8 +48890,8 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (node && ts.isInJSFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; @@ -47837,21 +48903,21 @@ var ts; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +48930,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +48987,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +48998,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49008,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49035,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49094,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49219,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49232,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,21 +49256,23 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { + function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } + return !isTupleType(restType) || restType.target.hasRestElement; } - return undefined; + return false; } - function hasEffectiveRestParameter(signature) { + function getEffectiveRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - return !isTupleType(restType) || restType.target.hasRestElement; + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } - return false; + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -48424,10 +49476,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49580,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48556,8 +49659,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48803,8 +49908,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -49105,7 +50210,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50348,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50365,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50426,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50436,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50542,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,9 +50584,9 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { if (noImplicitAny) { reportImplicitAnyError(declaration, anyType); @@ -49522,11 +50627,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50678,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50704,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50721,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50746,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50777,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +50870,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +50899,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51365,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51396,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50627,6 +51737,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51801,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +51830,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52063,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52086,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52143,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51302,7 +52412,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +52898,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +52981,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53021,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53037,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52888,7 +53998,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -53114,6 +54224,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54715,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54727,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54780,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +54841,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +54878,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +54910,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +54958,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55125,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54260,7 +55372,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55457,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55487,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55513,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55525,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55551,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55570,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55584,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55601,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55680,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55696,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55706,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,7 +55714,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { @@ -54611,9 +55724,7 @@ var ts; if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType); } return typeFromTypeNode; } @@ -54623,8 +55734,7 @@ var ts; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var classType = getTypeOfClassContainingHeritageClause(node); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54658,6 +55768,9 @@ var ts; } return errorType; } + function getTypeOfClassContainingHeritageClause(node) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent)); + } // Gets the type of object literal or array literal of destructuring assignment. // { a } from // for ( { a } of elems) { @@ -54719,6 +55832,22 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { @@ -54786,13 +55915,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +55970,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,7 +55983,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -54950,7 +56079,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56092,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56137,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56200,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56304,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56319,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56375,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55280,9 +56432,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56523,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55478,7 +56633,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57007,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57210,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57256,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57476,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57575,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57740,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57775,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61352,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61380,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -69197,19 +70391,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. if (node.transformFlags & 8388608 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -73516,7 +74718,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 67108864 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +74775,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +74806,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -76808,11 +78016,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78046,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78064,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78074,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78146,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,6 +78167,7 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76974,6 +78185,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78204,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78217,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77046,13 +78262,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78283,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +78808,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77865,10 +79110,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79111,7 +80357,7 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; @@ -79136,7 +80382,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79229,12 +80475,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81209,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81231,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +81656,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +81867,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +82572,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +82604,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +82778,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83200,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83391,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +83470,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +83984,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84017,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84027,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84035,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84047,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84059,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84075,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84109,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84136,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84224,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84240,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84302,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84311,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84335,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84362,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83196,7 +84470,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +84482,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +84574,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +84610,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +84655,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +84746,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +84758,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +84789,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +84810,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +84841,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +84868,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +84938,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +84954,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +84990,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85015,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85030,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85093,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85159,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85250,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +85479,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84371,6 +85662,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84457,6 +85749,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +85779,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +85808,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +85895,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +85904,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +85924,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +85944,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +85964,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +85975,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86024,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86037,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86096,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84863,9 +86144,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86161,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86360,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86377,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86388,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +86465,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +86475,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +86504,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,7 +86515,7 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } @@ -85752,7 +87039,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87052,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87233,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87391,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86575,121 +87869,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); - } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88043,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88060,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88081,27 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +88110,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86923,13 +88204,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88272,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88280,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88330,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88346,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88380,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88411,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +88425,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +88477,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,7 +88512,7 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; @@ -87273,7 +88585,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +88624,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +88651,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87550,6 +88863,7 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -87637,6 +88951,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +88973,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +88991,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } - } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); - } - } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); - } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; + return lookup.get(toPath(fileName)); } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; + function getSize() { + return lookup.size; } - function getKeys() { - return allKeys.getKeys(); + function clear() { + lookup.clear(); } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89062,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89077,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,386 +89098,598 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } + watchWildCardDirectories(resolved, cfg); // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } + watchInputFiles(resolved, cfg); } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); } } - function resetBuildContext(opts) { - if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); - } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + if (result.fileNames.length !== 0) { + ts.filterMutate(proj.errors, function (error) { return !ts.isErrorNoInputFiles(error); }); + } + else if (!proj.configFileSpecs.filesSpecs && !ts.some(proj.errors, ts.isErrorNoInputFiles)) { + proj.errors.push(ts.getErrorForNoInputFiles(proj.configFileSpecs, resolved)); + } + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { @@ -88190,420 +89698,221 @@ var ts; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; - } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +89948,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +89960,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90103,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90148,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90224,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90309,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90347,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +90438,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +90487,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +90726,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +90785,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +90907,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91044,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91408,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +91426,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +91435,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +91663,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +91777,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +91785,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90883,7 +92296,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92304,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -91273,7 +92686,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +92695,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +93453,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_9 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_9(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +93502,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +93519,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_10 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_10(moduleName); } } if (!foundGlobal) { @@ -92202,7 +93636,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +93669,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +93693,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +93812,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92471,7 +93918,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +93926,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +93954,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94026,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94114,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94127,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94154,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94172,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94199,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +94612,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +94637,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +94646,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +94784,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +94799,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +94836,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +94864,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +94888,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +94909,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +94939,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +94963,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + resolvedModuleSymbol.declarations.some(function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95205,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95240,16 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; } } return undefined; @@ -93928,10 +95403,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +95415,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -94151,17 +95625,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +95660,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +95732,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94748,9 +96224,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96268,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96282,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96349,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +96637,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +96668,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +96788,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,6 +96933,14 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); function nodeEntry(node, isInString) { return { type: "node", node: node.name || node, isInString: isInString }; } @@ -95490,9 +96974,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95521,28 +97005,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95571,7 +97055,7 @@ var ts; textSpan: getTextSpan(node, sourceFile), isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString, }; @@ -95635,7 +97119,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95725,7 +97264,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95894,7 +97433,7 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; @@ -96062,8 +97601,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +97651,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +97709,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +97736,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96602,7 +98141,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98199,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96673,7 +98213,7 @@ var ts; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } @@ -96777,8 +98317,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +98380,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +98483,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_11 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +98511,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_11(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +98541,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +98571,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +98613,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +98879,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99099,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99132,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99195,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99255,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99298,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_12 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99308,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_12(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99323,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +99647,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -99248,13 +100805,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_13 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_13(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +101351,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,9 +101362,34 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + localizedErrorMessage: undefined, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, localizedErrorMessage: undefined, @@ -99882,17 +101464,26 @@ var ts; return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +101492,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +101523,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +101545,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100239,7 +101834,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + var _loop_14 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100249,7 +101844,7 @@ var ts; } }; for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + var state_4 = _loop_14(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +101859,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +101876,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +101951,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102075,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102104,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100539,7 +102154,7 @@ var ts; var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102179,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102192,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102211,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +102382,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +102529,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +102759,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +102831,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +102899,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +102973,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_15 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +102992,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_15(opt); } return options; } @@ -104156,7 +105799,7 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } @@ -104194,7 +105837,7 @@ var ts; this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104262,24 +105905,31 @@ var ts; }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +105952,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106077,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106109,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106117,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_16 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106152,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_16(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106191,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106209,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_17 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_17(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106226,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); - return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + return applyChanges(nonFormattedText, changes); } - changesToText.newFileChanges = newFileChanges; + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,7 +106275,7 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } })(changesToText || (changesToText = {})); @@ -105399,7 +107060,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,30 +107113,41 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } @@ -105485,24 +107157,19 @@ var ts; var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_18 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_18(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107216,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107230,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107244,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107270,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107293,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107303,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || []).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { return []; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,6 +107337,7 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } + codeActionSucceeded = false; return []; } function transformCatch(node, transformer, prevArgName) { @@ -105670,17 +107353,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +107380,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +107396,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +107409,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return ts.createNodeArray([ts.createStatement(rightHandSide)]); + } if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); } return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; - var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + } + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, argName ? [argName.identifier] : []); if (shouldReturn) { return ts.createNodeArray([ts.createReturn(synthCall)]); } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105775,47 +107478,59 @@ var ts; } } return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return ts.createNodeArray(innerCbBody); } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + if (!shouldReturn) { + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } return ts.createNodeArray([]); } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } return ts.createNodeArray(ret); } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { @@ -105837,12 +107552,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +107559,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +107648,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +107765,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108251,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); } } }); return result; } function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + return !(s.flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +108345,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +108404,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106742,13 +108456,9 @@ var ts; } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +108468,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && { symbol: symbol, symbolForMeaning: info.symbolForMeaning, name: info.name, kind: kind }; + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +108491,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +108734,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +108776,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +108805,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_19 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +108832,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_19(info); } }); })); @@ -107151,7 +108876,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +108886,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109006,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109018,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +109882,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110014,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110036,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108301,7 +110135,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return undefined; // TODO: GH#20113 } var token = ts.getTokenAtPosition(sourceFile, start); @@ -108750,16 +110584,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +110611,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +110841,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +110867,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +111517,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_20 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +111536,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_20(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112162,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +112378,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +112712,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +112768,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_21 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +112808,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_21(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113082,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111322,10 +113358,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_22 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_23 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +113383,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_23(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_22(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +113806,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +114380,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +114559,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +114901,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +114940,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +114965,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115080,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115123,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113389,19 +115430,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index dd81fe55cedd6..acd901bf2c478 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -88,7 +88,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -101,6 +101,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -729,17 +730,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -784,7 +791,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1161,7 +1168,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1281,6 +1288,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1948,6 +1959,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2042,6 +2057,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2747,38 +3122,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -3006,9 +3381,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3027,22 +3401,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3809,17 +4183,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4755,7 +5133,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4794,6 +5172,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5037,7 +5419,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5065,6 +5446,13 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5156,6 +5544,8 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + Index_0_is_out_of_bounds_in_tuple_of_length_1: diag(2733, ts.DiagnosticCategory.Error, "Index_0_is_out_of_bounds_in_tuple_of_length_1_2733", "Index '{0}' is out-of-bounds in tuple of length {1}."), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5269,7 +5659,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5363,7 +5755,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5461,6 +5853,14 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5491,9 +5891,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5558,6 +5958,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5686,6 +6087,8 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; @@ -6407,6 +6810,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6436,6 +6840,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6891,6 +7296,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6929,6 +7335,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6986,6 +7410,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7568,6 +7997,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7588,7 +8020,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7670,22 +8101,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7790,6 +8208,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8014,12 +8438,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8046,13 +8478,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8421,6 +8853,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -9148,18 +9584,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9199,14 +9635,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9229,15 +9665,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9245,26 +9685,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9273,7 +9713,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9287,30 +9727,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9321,7 +9761,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9365,12 +9805,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9380,9 +9820,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9411,7 +9851,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9420,11 +9860,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9530,7 +9970,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9572,6 +10012,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9762,6 +10206,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9786,32 +10236,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9870,7 +10324,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9879,7 +10333,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10627,7 +11081,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10748,7 +11202,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10764,7 +11218,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11120,10 +11574,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11262,6 +11716,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11352,6 +11828,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11527,6 +12005,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11538,12 +12018,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11769,13 +12271,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12103,13 +12598,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12121,9 +12616,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12131,10 +12624,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12165,7 +12656,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12211,15 +12702,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12240,6 +12730,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12366,7 +12873,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13712,7 +14232,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14105,6 +14625,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14121,9 +14653,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14135,13 +14666,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14414,8 +14946,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14637,6 +15167,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14923,31 +15460,36 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; @@ -15080,14 +15622,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15258,6 +15800,10 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; })(ts || (ts = {})); var ts; (function (ts) { @@ -15346,6 +15892,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15416,6 +15963,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15774,7 +16322,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15943,8 +16491,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -17380,8 +17932,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19477,8 +20031,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -21074,7 +21629,7 @@ var ts; nextJSDocToken(); } } - function skipWhitespaceOrAsterisk() { + function skipWhitespaceOrAsterisk(next) { if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range @@ -21088,7 +21643,7 @@ var ts; else if (token() === 39 /* AsteriskToken */) { precedingLineBreak = false; } - nextJSDocToken(); + next(); } } function parseTag(indent) { @@ -21096,8 +21651,9 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespaceOrAsterisk(); + // Use 'nextToken' instead of 'nextJsDocToken' so we can parse a type like 'number' in `@enum number` + var tagName = parseJSDocIdentifierName(/*message*/ undefined, nextToken); + skipWhitespaceOrAsterisk(nextToken); var tag; switch (tagName.escapedText) { case "augments": @@ -21234,7 +21790,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21268,7 +21824,7 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { @@ -21277,10 +21833,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21294,14 +21848,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21389,7 +21943,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(nextJSDocToken); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21404,7 +21958,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21465,7 +22019,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21505,17 +22059,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21543,7 +22097,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21569,9 +22123,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -21624,7 +22176,8 @@ var ts; } return entity; } - function parseJSDocIdentifierName(message) { + function parseJSDocIdentifierName(message, next) { + if (next === void 0) { next = nextJSDocToken; } if (!ts.tokenIsIdentifierOrKeyword(token())) { return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } @@ -21633,7 +22186,7 @@ var ts; var result = createNode(71 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); - nextJSDocToken(); + next(); return result; } } @@ -22412,8 +22965,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +22979,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22474,21 +23062,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22503,6 +23076,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22521,6 +23096,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22533,6 +23109,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22540,6 +23117,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22557,6 +23135,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22666,6 +23245,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23254,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,6 +23263,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22690,6 +23272,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22698,6 +23281,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23290,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23324,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23337,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22758,6 +23345,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22767,6 +23355,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22782,6 +23371,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22793,6 +23383,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22803,6 +23394,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22887,30 +23479,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22969,12 +23543,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22987,6 +23563,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23032,6 +23609,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23039,6 +23617,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23066,6 +23645,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23093,7 +23673,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23146,20 +23764,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23195,16 +23814,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23216,7 +23834,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23224,7 +23842,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23260,7 +23878,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +23921,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23318,7 +23946,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23939,7 +24595,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23956,8 +24613,21 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + if (filesSpecs.length === 0 && hasZeroOrNoReferences) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23998,14 +24668,13 @@ var ts; } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24013,7 +24682,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24123,11 +24791,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24174,7 +24837,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24182,7 +24845,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24396,7 +25059,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24459,12 +25122,8 @@ var ts; } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24653,6 +25312,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24669,7 +25334,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24678,48 +25343,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); } - return; } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); } - return path; + return; } + return result; } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24763,7 +25474,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24783,7 +25495,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24810,11 +25521,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24830,7 +25541,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24869,11 +25580,11 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { // Return just the type directive names result.push(ts.getBaseFileName(normalized)); @@ -25099,15 +25810,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25145,7 +25856,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25164,7 +25875,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25175,74 +25886,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25254,8 +25951,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25263,7 +25960,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25277,7 +25974,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25294,29 +25991,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25324,7 +26022,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25365,52 +26063,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25424,12 +26116,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25443,40 +26135,41 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); - } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state); if (fromPackageJson) { return fromPackageJson; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(candidate, state.host); + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25488,6 +26181,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25499,23 +26193,24 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); + function loadModuleFromPackageJson(jsonContent, versionPaths, extensions, candidate, state) { + var file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) + : readPackageJsonMainField(jsonContent, candidate, state); if (!file) { if (extensions === Extensions.TypeScript) { // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + file = readPackageJsonMainField(jsonContent, candidate, state); if (!file) { return undefined; } @@ -25524,26 +26219,35 @@ var ts; return undefined; } } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailures = !ts.directoryProbablyExists(ts.getDirectoryPath(file), state.host); + if (versionPaths && ts.containsPath(candidate, file)) { + var moduleName = ts.getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state)); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25563,87 +26267,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25651,11 +26397,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25664,43 +26410,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25708,24 +26455,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25740,9 +26487,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25957,13 +26704,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -26008,7 +26759,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26088,7 +26839,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26166,12 +26918,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26432,6 +27184,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -27230,7 +27984,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27250,7 +28004,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27338,9 +28092,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27360,7 +28111,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27585,7 +28336,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27632,7 +28383,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27649,15 +28400,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27730,15 +28481,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27754,7 +28505,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27765,9 +28516,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27848,14 +28599,18 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { @@ -27914,7 +28669,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27944,7 +28699,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -28001,7 +28756,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28022,7 +28777,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28048,40 +28803,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28090,7 +28844,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28103,7 +28857,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28187,8 +28941,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28200,10 +28957,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28220,7 +28977,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28238,10 +28995,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28279,10 +29036,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28291,14 +29048,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28317,9 +29074,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28357,7 +29112,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28395,6 +29150,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -29447,6 +30205,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29467,7 +30237,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29683,8 +30454,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29752,7 +30523,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29782,8 +30554,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29946,6 +30731,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29988,6 +30775,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30123,35 +30911,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30184,7 +30972,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30197,8 +30985,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30237,12 +31026,12 @@ var ts; var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; targetList.instances.push(errorNode); }); @@ -30259,7 +31048,7 @@ var ts; } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); }); } @@ -30373,8 +31162,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30517,7 +31306,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30526,7 +31315,7 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + if (meaning & 67220415 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { // parameters are visible only inside function body, parameter list and return type // technically for parameter list case here we might mix parameters and variables declared in function, // however it is detected separately when checking initializers of parameters @@ -30612,7 +31401,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30622,7 +31411,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30649,7 +31441,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30669,7 +31461,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30752,7 +31544,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30807,14 +31599,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30910,9 +31702,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30931,29 +31723,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30981,6 +31776,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31050,7 +31848,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31104,7 +31902,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31194,7 +31992,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31213,7 +32011,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31228,10 +32026,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31262,7 +32060,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31311,7 +32109,7 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -31324,11 +32122,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31344,7 +32142,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31379,15 +32177,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31395,9 +32193,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31405,6 +32215,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31434,7 +32251,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32270,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31485,7 +32302,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31493,7 +32310,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31505,18 +32322,17 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; @@ -31750,7 +32566,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31850,7 +32666,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31900,7 +32716,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31965,11 +32784,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -32007,7 +32826,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32115,7 +32944,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32125,7 +32954,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32275,13 +33104,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32301,7 +33130,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32368,14 +33197,14 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; @@ -32448,23 +33277,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32546,8 +33375,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32586,7 +33415,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32599,7 +33428,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32697,18 +33526,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32836,7 +33660,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32847,7 +33671,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32888,6 +33712,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32897,6 +33724,16 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. @@ -33009,7 +33846,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33017,7 +33861,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33174,7 +34018,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33358,10 +34202,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33382,7 +34226,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33431,6 +34275,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33683,7 +34529,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33714,16 +34560,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33743,16 +34595,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33766,8 +34618,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33775,9 +34627,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33785,7 +34637,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33803,8 +34655,8 @@ var ts; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33823,7 +34675,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33837,10 +34689,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33889,8 +34741,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33898,7 +34750,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -34050,7 +34902,14 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { return checkExpression(declaration.expression); @@ -34060,9 +34919,9 @@ var ts; return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34076,7 +34935,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34137,7 +34996,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34195,7 +35054,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34223,7 +35082,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34232,11 +35091,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34261,7 +35120,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34270,22 +35129,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34444,15 +35295,15 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { + var isJavascript = ts.isInJSFile(location); + if (isJSConstructorType(type) && !typeArgCount) { return getSignaturesOfType(type, 0 /* Call */); } return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); @@ -34460,7 +35311,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34542,8 +35393,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34642,7 +35493,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34781,9 +35632,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -35009,7 +35860,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35029,7 +35880,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35283,7 +36134,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35778,10 +36629,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35798,7 +36654,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35877,6 +36734,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35884,8 +36742,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35907,8 +36775,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35923,7 +36791,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35933,9 +36801,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35985,6 +36850,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35992,14 +36871,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36205,7 +37085,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36305,7 +37185,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36318,7 +37198,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36355,7 +37235,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36386,7 +37266,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36473,7 +37353,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36550,7 +37430,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36569,8 +37449,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36611,7 +37495,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36805,7 +37689,7 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; @@ -36838,7 +37722,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36893,14 +37777,28 @@ var ts; if (type) { return type; } + // JS are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36908,7 +37806,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36924,10 +37822,6 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); - } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -37042,10 +37936,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -37100,10 +37994,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37157,7 +38051,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37346,10 +38240,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37364,15 +38255,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37418,7 +38300,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37446,7 +38328,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37543,10 +38425,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37555,8 +38434,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37810,7 +38689,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37823,7 +38702,7 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; @@ -37882,7 +38761,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37900,7 +38779,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37908,20 +38790,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37935,37 +38803,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37986,7 +38841,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38013,17 +38869,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38201,7 +39068,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38231,7 +39098,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38245,7 +39112,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38387,8 +39254,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38398,7 +39265,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38604,7 +39471,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38705,7 +39572,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38715,7 +39582,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38774,8 +39641,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38785,30 +39662,24 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); - } + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38871,49 +39742,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } - } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38987,7 +39874,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39062,33 +39949,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39097,15 +40049,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39114,10 +40066,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39128,13 +40080,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39168,8 +40123,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39201,9 +40156,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39252,8 +40212,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39283,9 +40243,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39308,11 +40269,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39338,13 +40299,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39508,10 +40469,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39646,10 +40607,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39705,13 +40666,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39810,7 +40768,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39820,32 +40778,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39863,7 +40795,7 @@ var ts; return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39908,6 +40840,9 @@ var ts; } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39936,7 +40871,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39963,6 +40899,14 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -40153,6 +41097,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40181,20 +41156,24 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K] + if (relation !== identityRelation) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40212,7 +41191,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40285,6 +41263,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40318,36 +41316,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40370,10 +41358,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40504,33 +41492,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40562,8 +41523,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40755,6 +41716,33 @@ var ts; return false; } } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41043,8 +42031,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41120,10 +42108,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41148,13 +42136,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41166,7 +42158,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41180,11 +42172,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41470,19 +42463,23 @@ var ts; function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) : + sourceRestType ? targetCount : + Math.min(sourceCount, targetCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41797,6 +42794,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41832,7 +42832,14 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41928,33 +42935,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); - } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41964,12 +42976,15 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -42000,8 +43015,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42024,7 +43039,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42042,7 +43057,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42055,10 +43070,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42069,16 +43083,17 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { - if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & 32768 /* Never */)) { + // If we have contravariant inferences, but no covariant inferences or a single + // covariant inference of 'never', we find the best common subtype and treat that + // as a single covariant candidate. + inference.candidates = [getContravariantInference(inference)]; inference.contraCandidates = undefined; } if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + inferredType = getCovariantInference(inference, signature); } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42095,7 +43110,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42124,11 +43139,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42302,6 +43346,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42310,8 +43366,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42319,8 +43382,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42357,13 +43420,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42489,10 +43554,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42538,6 +43603,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42580,8 +43662,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42661,8 +43743,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42742,8 +43824,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42846,11 +43928,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42859,6 +43941,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42882,7 +43972,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42927,6 +44018,9 @@ var ts; else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43185,12 +44279,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43201,11 +44305,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43224,6 +44325,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43449,7 +44626,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43522,7 +44699,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43781,31 +44958,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43820,13 +44995,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -44052,7 +45254,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44109,7 +45311,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44225,7 +45427,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44246,13 +45448,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44262,9 +45471,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44282,19 +45491,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); - } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44513,7 +45749,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44532,6 +45768,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44540,7 +45782,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44612,11 +45854,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44722,8 +45964,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44759,7 +46001,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44781,7 +46023,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44790,7 +46032,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44828,6 +46070,9 @@ var ts; } return createTupleType(elementTypes, minLength, hasRestElement); } + else if (forceTuple) { + return createTupleType(elementTypes, minLength, hasRestElement); + } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } @@ -44920,9 +46165,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44940,7 +46185,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45150,12 +46395,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45172,7 +46419,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45180,7 +46427,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45189,7 +46436,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45211,7 +46458,7 @@ var ts; createArrayType(getUnionType(childrenTypes)); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45228,7 +46475,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45261,7 +46508,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45309,7 +46556,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45319,7 +46566,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45386,7 +46633,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45410,7 +46657,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45632,7 +46879,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45748,7 +46995,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45869,10 +47116,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45917,7 +47164,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46072,6 +47319,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46185,7 +47438,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46290,7 +47543,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46356,7 +47609,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46364,7 +47617,14 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + if (isTupleType(objectType) && !objectType.target.hasRestElement && ts.isNumericLiteral(indexExpression)) { + var index = +indexExpression.text; + var maximumIndex = ts.length(objectType.target.typeParameters); + if (index >= maximumIndex) { + error(indexExpression, ts.Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); + } + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46485,16 +47745,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46512,7 +47769,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46523,11 +47780,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46558,7 +47815,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46567,7 +47824,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46625,58 +47882,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46684,12 +47923,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46698,23 +47934,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46769,36 +48005,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46812,19 +48039,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46832,283 +48060,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; - } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); - } - } - else { - return args.length; - } - } - /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. - */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + return getEffectiveDecoratorArguments(node); } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. - */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. + if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; + return args; } /** - * Gets the effective argument type for an argument in a call expression. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - return args[argIndex]; + return ts.Debug.fail(); } /** - * Gets the error node to use when reporting errors for an effective argument. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47117,6 +48149,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47125,7 +48158,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47136,16 +48172,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47178,36 +48223,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47277,14 +48306,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47304,60 +48336,74 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } - } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; - } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = checkCandidate; + continue; } } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47427,17 +48473,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47510,12 +48566,19 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47588,11 +48651,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47662,10 +48727,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47758,7 +48824,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47837,8 +48903,8 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (node && ts.isInJSFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; @@ -47850,21 +48916,21 @@ var ts; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47877,14 +48943,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47937,7 +49000,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47948,7 +49011,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47958,8 +49021,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47985,7 +49048,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48044,7 +49107,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48169,14 +49232,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48185,17 +49245,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48219,21 +49269,23 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { + function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } + return !isTupleType(restType) || restType.target.hasRestElement; } - return undefined; + return false; } - function hasEffectiveRestParameter(signature) { + function getEffectiveRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - return !isTupleType(restType) || restType.target.hasRestElement; + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } - return false; + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -48437,10 +49489,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48490,7 +49593,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48569,8 +49672,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48816,8 +49921,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -49118,7 +50223,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49256,9 +50361,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49273,15 +50378,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49334,8 +50439,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +50449,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49450,7 +50555,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49492,9 +50597,9 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { if (noImplicitAny) { reportImplicitAnyError(declaration, anyType); @@ -49535,11 +50640,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49586,15 +50691,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49608,9 +50717,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49621,13 +50734,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49646,13 +50759,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49677,7 +50790,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49770,9 +50883,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49802,7 +50912,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50268,7 +51378,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50299,7 +51409,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50640,6 +51750,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50697,13 +51814,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50733,10 +51843,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50966,7 +52076,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50989,7 +52099,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51046,7 +52156,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51315,7 +52425,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51801,7 +52911,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51884,7 +52994,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51924,7 +53034,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51940,7 +53050,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52901,7 +54011,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -53127,6 +54237,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53616,8 +54728,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53628,7 +54740,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53681,14 +54793,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53742,13 +54854,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53779,7 +54891,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53811,7 +54923,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53859,7 +54971,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54026,7 +55138,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54273,7 +55385,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54358,12 +55470,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54388,7 +55500,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54414,7 +55526,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54426,7 +55538,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54452,10 +55564,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54471,7 +55583,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54485,7 +55597,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54502,7 +55614,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54581,7 +55693,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54597,6 +55709,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54606,7 +55719,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54614,7 +55727,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { @@ -54624,9 +55737,7 @@ var ts; if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType); } return typeFromTypeNode; } @@ -54636,8 +55747,7 @@ var ts; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var classType = getTypeOfClassContainingHeritageClause(node); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54671,6 +55781,9 @@ var ts; } return errorType; } + function getTypeOfClassContainingHeritageClause(node) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent)); + } // Gets the type of object literal or array literal of destructuring assignment. // { a } from // for ( { a } of elems) { @@ -54732,6 +55845,22 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { @@ -54799,13 +55928,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54854,7 +55983,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54867,7 +55996,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -54963,7 +56092,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54976,7 +56105,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55021,6 +56150,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55065,9 +56213,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55169,7 +56317,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55184,18 +56332,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55238,6 +56388,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55293,9 +56445,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55384,6 +56536,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55491,7 +56646,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55865,11 +57020,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56047,6 +57223,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56090,8 +57269,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56308,6 +57489,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56404,26 +57588,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56563,10 +57753,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56597,8 +57788,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60174,6 +61365,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60187,19 +61393,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -69210,19 +70404,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. if (node.transformFlags & 8388608 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -73529,7 +74731,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 67108864 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73583,6 +74788,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73613,22 +74819,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -76821,11 +78029,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76851,7 +78059,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76869,6 +78077,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76878,10 +78087,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76950,15 +78159,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76970,6 +78180,7 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76987,6 +78198,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -77005,8 +78217,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77017,11 +78230,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77059,13 +78275,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77075,6 +78296,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77591,10 +78821,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77878,10 +79123,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79124,7 +80370,7 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; @@ -79149,7 +80395,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79242,12 +80488,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79976,7 +81222,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79998,7 +81244,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80423,7 +81669,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80634,7 +81880,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81337,13 +82585,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81369,11 +82617,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81538,7 +82791,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81959,19 +83213,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82150,7 +83404,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82229,7 +83483,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82743,17 +83997,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82769,7 +84030,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82779,7 +84040,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82787,8 +84048,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82799,8 +84060,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82811,11 +84072,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82827,36 +84088,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82864,8 +84122,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82891,7 +84149,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82979,8 +84237,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82995,11 +84253,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83057,7 +84315,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83066,6 +84324,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83086,8 +84348,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83097,21 +84375,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83209,7 +84483,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83221,11 +84495,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83312,7 +84587,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83346,9 +84623,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83391,13 +84668,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83482,8 +84759,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83491,15 +84771,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83529,15 +84802,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83545,16 +84823,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83577,7 +84854,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83604,7 +84881,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83670,7 +84951,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83686,7 +84967,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83721,14 +85003,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83739,11 +85028,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83753,12 +85043,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83815,7 +85106,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83881,9 +85172,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83972,7 +85263,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84201,7 +85492,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84384,6 +85675,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84470,6 +85762,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84499,24 +85792,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84526,7 +85821,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84613,7 +85908,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84622,7 +85917,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84642,7 +85937,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84662,27 +85957,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84690,7 +85977,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84701,22 +85988,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84756,9 +86037,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84768,17 +86050,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84828,15 +86109,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84876,9 +86157,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84893,15 +86174,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85092,7 +86373,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85109,7 +86390,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85117,17 +86401,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85197,7 +86478,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85207,6 +86488,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85230,7 +86517,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85241,7 +86528,7 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } @@ -85765,7 +87052,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85778,7 +87065,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85952,16 +87246,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86110,7 +87404,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86588,121 +87882,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); - } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); + } + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; + } + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86766,16 +88056,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86793,7 +88073,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86813,25 +88094,27 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86840,20 +88123,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86936,13 +88217,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86981,11 +88285,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86994,7 +88293,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87044,7 +88343,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87060,7 +88359,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87094,6 +88393,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87106,7 +88424,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87120,17 +88438,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87179,18 +88490,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87213,7 +88525,7 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; @@ -87286,7 +88598,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87324,9 +88637,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87351,7 +88664,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87563,6 +88876,7 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -87650,6 +88964,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87670,7 +88986,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87687,94 +89004,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); - } - } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getSize() { + return lookup.size; } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); + function clear() { + lookup.clear(); } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); + } + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87787,7 +89075,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87798,13 +89090,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87815,386 +89111,598 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } + watchWildCardDirectories(resolved, cfg); // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } + watchInputFiles(resolved, cfg); } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); } } - function resetBuildContext(opts) { - if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); - } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; + } + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + if (result.fileNames.length !== 0) { + ts.filterMutate(proj.errors, function (error) { return !ts.isErrorNoInputFiles(error); }); + } + else if (!proj.configFileSpecs.filesSpecs && !ts.some(proj.errors, ts.isErrorNoInputFiles)) { + proj.errors.push(ts.getErrorForNoInputFiles(proj.configFileSpecs, resolved)); + } + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { @@ -88203,420 +89711,221 @@ var ts; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; - } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88652,7 +89961,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88660,6 +89971,142 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.js.map "use strict"; /* @internal */ @@ -88671,6 +90118,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88715,8 +90163,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88791,7 +90239,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88876,7 +90324,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -89005,71 +90453,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); //# sourceMappingURL=jsTyping.js.map "use strict"; var ts; @@ -89277,8 +90660,10 @@ var ts; } var info = ts.getProperty(npmLock.dependencies, key); var version_1 = info && info.version; - var semver = ts.Semver.parse(version_1); // TODO: GH#18217 - var newTyping = { typingLocation: typingFile, version: semver }; + if (!version_1) { + continue; + } + var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) }; this.packageNameToTypingLocation.set(packageName, newTyping); } } @@ -89380,7 +90765,7 @@ var ts; } // packageName is guaranteed to exist in typesRegistry by filterTypings var distTags = _this.typesRegistry.get(packageName); - var newVersion = ts.Semver.parse(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); + var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); var newTyping = { typingLocation: typingFile, version: newVersion }; _this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); @@ -89678,6 +91063,11 @@ var ts; } break; } + case "inspectValue": { + var response = { kind: server.ActionValueInspected, result: ts.inspectModule(req.options.fileNameToRequire) }; + _this.sendResponse(response); + break; + } default: ts.Debug.assertNever(req); } diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index aaf6a7101a8a3..23d0bae7b27ad 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -68,7 +68,7 @@ "A_rest_parameter_cannot_have_an_initializer_1048": "rest 参数不能具有初始化表达式。", "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 参数必须是参数列表中的最后一个参数。", "A_rest_parameter_must_be_of_an_array_type_2370": "rest 参数必须是数组类型。", - "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式可能不具有尾随逗号。", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式不可带尾随逗号。", "A_return_statement_can_only_be_used_within_a_function_body_1108": "\"return\" 语句只能在函数体中使用。", "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列条目,这些条目将重新映射导入内容,以查找与 \"baseUrl\" 有关的位置。", "A_set_accessor_cannot_have_a_return_type_annotation_1095": "\"set\" 访问器不能具有返回类型批注。", @@ -161,7 +161,7 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引签名参数不能具有可访问性修饰符。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引签名参数不能具有初始化表达式。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", - "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改而编写“[{0}: {1}]:{2}”。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改为编写“[{0}: {1}]:{2}”。", "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引签名参数类型不能为联合类型。请考虑改用映射的对象类型。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", @@ -628,7 +628,7 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "在没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", "Options_0_and_1_cannot_be_combined_6370": "选项“{0}”与“{1}”不能组合在一起。", "Options_Colon_6027": "选项:", "Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。", diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 22fc19bcc8a31..804ba0dd9afb9 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -3,7 +3,7 @@ namespace ts { // If changing the text in this section, be sure to test `configureNightly` too. export const versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ - export const version = `${versionMajorMinor}.0-dev`; + export const version = `${versionMajorMinor}.0`; } namespace ts {