diff --git a/.editorconfig b/.editorconfig new file mode 100755 index 0000000..182842f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,374 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 120 +ij_visual_guides = 120 +ij_wrap_on_typing = false + + +[*.md] +trim_trailing_whitespace = false + +[.editorconfig] +ij_editorconfig_align_group_field_declarations = false +ij_editorconfig_space_after_colon = false +ij_editorconfig_space_after_comma = true +ij_editorconfig_space_before_colon = false +ij_editorconfig_space_before_comma = false +ij_editorconfig_spaces_around_assignment_operators = true + + +[{*.js, *.cjs}] +tab_width = 2 +ij_continuation_indent_size = 2 +ij_javascript_align_imports = false +ij_javascript_align_multiline_array_initializer_expression = false +ij_javascript_align_multiline_binary_operation = false +ij_javascript_align_multiline_chained_methods = false +ij_javascript_align_multiline_extends_list = false +ij_javascript_align_multiline_for = true +ij_javascript_align_multiline_parameters = true +ij_javascript_align_multiline_parameters_in_calls = false +ij_javascript_align_multiline_ternary_operation = true +ij_javascript_align_object_properties = 0 +ij_javascript_align_union_types = false +ij_javascript_align_var_statements = 0 +ij_javascript_array_initializer_new_line_after_left_brace = false +ij_javascript_array_initializer_right_brace_on_new_line = false +ij_javascript_array_initializer_wrap = off +ij_javascript_assignment_wrap = off +ij_javascript_binary_operation_sign_on_next_line = false +ij_javascript_binary_operation_wrap = off +ij_javascript_blacklist_imports = rxjs/Rx, node_modules/**/*, @angular/material, @angular/material/typings/** +ij_javascript_blank_lines_after_imports = 2 +ij_javascript_blank_lines_around_class = 1 +ij_javascript_blank_lines_around_field = 0 +ij_javascript_blank_lines_around_function = 1 +ij_javascript_blank_lines_around_method = 1 +ij_javascript_block_brace_style = end_of_line +ij_javascript_call_parameters_new_line_after_left_paren = false +ij_javascript_call_parameters_right_paren_on_new_line = false +ij_javascript_call_parameters_wrap = off +ij_javascript_catch_on_new_line = true +ij_javascript_chained_call_dot_on_new_line = true +ij_javascript_class_brace_style = end_of_line +ij_javascript_comma_on_new_line = false +ij_javascript_do_while_brace_force = never +ij_javascript_else_on_new_line = false +ij_javascript_enforce_trailing_comma = keep +ij_javascript_extends_keyword_wrap = off +ij_javascript_extends_list_wrap = off +ij_javascript_field_prefix = _ +ij_javascript_file_name_style = relaxed +ij_javascript_finally_on_new_line = true +ij_javascript_for_brace_force = never +ij_javascript_for_statement_new_line_after_left_paren = false +ij_javascript_for_statement_right_paren_on_new_line = false +ij_javascript_for_statement_wrap = off +ij_javascript_force_quote_style = false +ij_javascript_force_semicolon_style = false +ij_javascript_function_expression_brace_style = end_of_line +ij_javascript_if_brace_force = never +ij_javascript_import_merge_members = global +ij_javascript_import_prefer_absolute_path = global +ij_javascript_import_sort_members = true +ij_javascript_import_sort_module_name = false +ij_javascript_import_use_node_resolution = true +ij_javascript_imports_wrap = normal +ij_javascript_indent_case_from_switch = true +ij_javascript_indent_chained_calls = true +ij_javascript_indent_package_children = 0 +ij_javascript_jsx_attribute_value = braces +ij_javascript_keep_blank_lines_in_code = 2 +ij_javascript_keep_first_column_comment = true +ij_javascript_keep_indents_on_empty_lines = false +ij_javascript_keep_line_breaks = true +ij_javascript_keep_simple_blocks_in_one_line = true +ij_javascript_keep_simple_methods_in_one_line = true +ij_javascript_line_comment_add_space = true +ij_javascript_line_comment_at_first_column = false +ij_javascript_method_brace_style = end_of_line +ij_javascript_method_call_chain_wrap = off +ij_javascript_method_parameters_new_line_after_left_paren = false +ij_javascript_method_parameters_right_paren_on_new_line = false +ij_javascript_method_parameters_wrap = off +ij_javascript_object_literal_wrap = on_every_item +ij_javascript_parentheses_expression_new_line_after_left_paren = false +ij_javascript_parentheses_expression_right_paren_on_new_line = false +ij_javascript_place_assignment_sign_on_next_line = false +ij_javascript_prefer_as_type_cast = false +ij_javascript_prefer_parameters_wrap = false +ij_javascript_reformat_c_style_comments = false +ij_javascript_space_after_colon = true +ij_javascript_space_after_comma = true +ij_javascript_space_after_dots_in_rest_parameter = false +ij_javascript_space_after_generator_mult = true +ij_javascript_space_after_property_colon = true +ij_javascript_space_after_quest = true +ij_javascript_space_after_type_colon = true +ij_javascript_space_after_unary_not = false +ij_javascript_space_before_async_arrow_lparen = true +ij_javascript_space_before_catch_keyword = true +ij_javascript_space_before_catch_left_brace = true +ij_javascript_space_before_catch_parentheses = true +ij_javascript_space_before_class_lbrace = true +ij_javascript_space_before_class_left_brace = true +ij_javascript_space_before_colon = true +ij_javascript_space_before_comma = false +ij_javascript_space_before_do_left_brace = true +ij_javascript_space_before_else_keyword = true +ij_javascript_space_before_else_left_brace = true +ij_javascript_space_before_finally_keyword = true +ij_javascript_space_before_finally_left_brace = true +ij_javascript_space_before_for_left_brace = true +ij_javascript_space_before_for_parentheses = true +ij_javascript_space_before_for_semicolon = false +ij_javascript_space_before_function_left_parenth = true +ij_javascript_space_before_generator_mult = false +ij_javascript_space_before_if_left_brace = true +ij_javascript_space_before_if_parentheses = true +ij_javascript_space_before_method_call_parentheses = false +ij_javascript_space_before_method_left_brace = true +ij_javascript_space_before_method_parentheses = false +ij_javascript_space_before_property_colon = false +ij_javascript_space_before_quest = true +ij_javascript_space_before_switch_left_brace = true +ij_javascript_space_before_switch_parentheses = true +ij_javascript_space_before_try_left_brace = true +ij_javascript_space_before_type_colon = false +ij_javascript_space_before_unary_not = false +ij_javascript_space_before_while_keyword = true +ij_javascript_space_before_while_left_brace = true +ij_javascript_space_before_while_parentheses = true +ij_javascript_spaces_around_additive_operators = true +ij_javascript_spaces_around_arrow_function_operator = true +ij_javascript_spaces_around_assignment_operators = true +ij_javascript_spaces_around_bitwise_operators = true +ij_javascript_spaces_around_equality_operators = true +ij_javascript_spaces_around_logical_operators = true +ij_javascript_spaces_around_multiplicative_operators = true +ij_javascript_spaces_around_relational_operators = true +ij_javascript_spaces_around_shift_operators = true +ij_javascript_spaces_around_unary_operator = false +ij_javascript_spaces_within_array_initializer_brackets = true +ij_javascript_spaces_within_brackets = false +ij_javascript_spaces_within_catch_parentheses = false +ij_javascript_spaces_within_for_parentheses = false +ij_javascript_spaces_within_if_parentheses = false +ij_javascript_spaces_within_imports = true +ij_javascript_spaces_within_interpolation_expressions = false +ij_javascript_spaces_within_method_call_parentheses = false +ij_javascript_spaces_within_method_parentheses = false +ij_javascript_spaces_within_object_literal_braces = true +ij_javascript_spaces_within_object_type_braces = true +ij_javascript_spaces_within_parentheses = false +ij_javascript_spaces_within_switch_parentheses = false +ij_javascript_spaces_within_type_assertion = false +ij_javascript_spaces_within_union_types = true +ij_javascript_spaces_within_while_parentheses = false +ij_javascript_special_else_if_treatment = true +ij_javascript_ternary_operation_signs_on_next_line = false +ij_javascript_ternary_operation_wrap = off +ij_javascript_union_types_wrap = on_every_item +ij_javascript_use_chained_calls_group_indents = false +ij_javascript_use_double_quotes = true +ij_javascript_use_explicit_js_extension = global +ij_javascript_use_path_mapping = always +ij_javascript_use_public_modifier = false +ij_javascript_use_semicolon_after_statement = true +ij_javascript_var_declaration_wrap = normal +ij_javascript_while_brace_force = never +ij_javascript_while_on_new_line = false +ij_javascript_wrap_comments = false + + +[{*.zsh, *.bash, *.sh}] +ij_shell_binary_ops_start_line = false +ij_shell_keep_column_alignment_padding = false +ij_shell_minify_program = false +ij_shell_redirect_followed_by_space = false +ij_shell_switch_cases_indented = false + + +[{.babelrc, .prettierrc, .stylelintrc, .eslintrc, jest.config, *.json, *.jsb3, *.jsb2, *.bowerrc}] +ij_json_keep_blank_lines_in_code = 2 +ij_json_keep_indents_on_empty_lines = false +ij_json_keep_line_breaks = true +ij_json_space_after_colon = true +ij_json_space_after_comma = true +ij_json_space_before_colon = true +ij_json_space_before_comma = false +ij_json_spaces_within_braces = true +ij_json_spaces_within_brackets = true +ij_json_wrap_long_lines = false + +[{*.ats, *.ts, *.tsx}] +tab_width = 2 +ij_continuation_indent_size = 2 +ij_typescript_align_imports = false +ij_typescript_align_multiline_array_initializer_expression = false +ij_typescript_align_multiline_binary_operation = false +ij_typescript_align_multiline_chained_methods = false +ij_typescript_align_multiline_extends_list = false +ij_typescript_align_multiline_for = true +ij_typescript_align_multiline_parameters = true +ij_typescript_align_multiline_parameters_in_calls = false +ij_typescript_align_multiline_ternary_operation = true +ij_typescript_align_object_properties = 0 +ij_typescript_align_union_types = false +ij_typescript_align_var_statements = 0 +ij_typescript_array_initializer_new_line_after_left_brace = false +ij_typescript_array_initializer_right_brace_on_new_line = false +ij_typescript_array_initializer_wrap = off +ij_typescript_assignment_wrap = off +ij_typescript_binary_operation_sign_on_next_line = false +ij_typescript_binary_operation_wrap = off +ij_typescript_blacklist_imports = rxjs/Rx, node_modules/**/*, @angular/material, @angular/material/typings/** +ij_typescript_blank_lines_after_imports = 2 +ij_typescript_blank_lines_around_class = 1 +ij_typescript_blank_lines_around_field = 0 +ij_typescript_blank_lines_around_field_in_interface = 0 +ij_typescript_blank_lines_around_function = 0 +ij_typescript_blank_lines_around_method = 1 +ij_typescript_blank_lines_around_method_in_interface = 1 +ij_typescript_block_brace_style = end_of_line +ij_typescript_call_parameters_new_line_after_left_paren = false +ij_typescript_call_parameters_right_paren_on_new_line = false +ij_typescript_call_parameters_wrap = off +ij_typescript_catch_on_new_line = true +ij_typescript_chained_call_dot_on_new_line = true +ij_typescript_class_brace_style = end_of_line +ij_typescript_comma_on_new_line = false +ij_typescript_do_while_brace_force = never +ij_typescript_else_on_new_line = false +ij_typescript_enforce_trailing_comma = keep +ij_typescript_extends_keyword_wrap = off +ij_typescript_extends_list_wrap = off +ij_typescript_field_prefix = _ +ij_typescript_file_name_style = relaxed +ij_typescript_finally_on_new_line = true +ij_typescript_for_brace_force = never +ij_typescript_for_statement_new_line_after_left_paren = false +ij_typescript_for_statement_right_paren_on_new_line = false +ij_typescript_for_statement_wrap = off +ij_typescript_force_quote_style = true +ij_typescript_force_semicolon_style = false +ij_typescript_function_expression_brace_style = end_of_line +ij_typescript_if_brace_force = never +ij_typescript_import_merge_members = global +ij_typescript_import_prefer_absolute_path = global +ij_typescript_import_sort_members = true +ij_typescript_import_sort_module_name = false +ij_typescript_import_use_node_resolution = true +ij_typescript_imports_wrap = normal +ij_typescript_indent_case_from_switch = true +ij_typescript_indent_chained_calls = true +ij_typescript_indent_package_children = 0 +ij_typescript_jsdoc_include_types = false +ij_typescript_jsx_attribute_value = braces +ij_typescript_keep_blank_lines_in_code = 2 +ij_typescript_keep_first_column_comment = true +ij_typescript_keep_indents_on_empty_lines = false +ij_typescript_keep_line_breaks = true +ij_typescript_keep_simple_blocks_in_one_line = true +ij_typescript_keep_simple_methods_in_one_line = true +ij_typescript_line_comment_add_space = true +ij_typescript_line_comment_at_first_column = false +ij_typescript_method_brace_style = end_of_line +ij_typescript_method_call_chain_wrap = off +ij_typescript_method_parameters_new_line_after_left_paren = false +ij_typescript_method_parameters_right_paren_on_new_line = false +ij_typescript_method_parameters_wrap = off +ij_typescript_object_literal_wrap = on_every_item +ij_typescript_parentheses_expression_new_line_after_left_paren = false +ij_typescript_parentheses_expression_right_paren_on_new_line = false +ij_typescript_place_assignment_sign_on_next_line = false +ij_typescript_prefer_as_type_cast = false +ij_typescript_prefer_parameters_wrap = false +ij_typescript_reformat_c_style_comments = false +ij_typescript_space_after_colon = true +ij_typescript_space_after_comma = true +ij_typescript_space_after_dots_in_rest_parameter = false +ij_typescript_space_after_generator_mult = true +ij_typescript_space_after_property_colon = true +ij_typescript_space_after_quest = true +ij_typescript_space_after_type_colon = true +ij_typescript_space_after_unary_not = false +ij_typescript_space_before_async_arrow_lparen = true +ij_typescript_space_before_catch_keyword = true +ij_typescript_space_before_catch_left_brace = true +ij_typescript_space_before_catch_parentheses = true +ij_typescript_space_before_class_lbrace = true +ij_typescript_space_before_class_left_brace = true +ij_typescript_space_before_colon = true +ij_typescript_space_before_comma = false +ij_typescript_space_before_do_left_brace = true +ij_typescript_space_before_else_keyword = true +ij_typescript_space_before_else_left_brace = true +ij_typescript_space_before_finally_keyword = true +ij_typescript_space_before_finally_left_brace = true +ij_typescript_space_before_for_left_brace = true +ij_typescript_space_before_for_parentheses = true +ij_typescript_space_before_for_semicolon = false +ij_typescript_space_before_function_left_parenth = true +ij_typescript_space_before_generator_mult = false +ij_typescript_space_before_if_left_brace = true +ij_typescript_space_before_if_parentheses = true +ij_typescript_space_before_method_call_parentheses = false +ij_typescript_space_before_method_left_brace = true +ij_typescript_space_before_method_parentheses = false +ij_typescript_space_before_property_colon = false +ij_typescript_space_before_quest = true +ij_typescript_space_before_switch_left_brace = true +ij_typescript_space_before_switch_parentheses = true +ij_typescript_space_before_try_left_brace = true +ij_typescript_space_before_type_colon = false +ij_typescript_space_before_unary_not = false +ij_typescript_space_before_while_keyword = true +ij_typescript_space_before_while_left_brace = true +ij_typescript_space_before_while_parentheses = true +ij_typescript_spaces_around_additive_operators = true +ij_typescript_spaces_around_arrow_function_operator = true +ij_typescript_spaces_around_assignment_operators = true +ij_typescript_spaces_around_bitwise_operators = true +ij_typescript_spaces_around_equality_operators = true +ij_typescript_spaces_around_logical_operators = true +ij_typescript_spaces_around_multiplicative_operators = true +ij_typescript_spaces_around_relational_operators = true +ij_typescript_spaces_around_shift_operators = true +ij_typescript_spaces_around_unary_operator = false +ij_typescript_spaces_within_array_initializer_brackets = true +ij_typescript_spaces_within_brackets = false +ij_typescript_spaces_within_catch_parentheses = false +ij_typescript_spaces_within_for_parentheses = false +ij_typescript_spaces_within_if_parentheses = false +ij_typescript_spaces_within_imports = true +ij_typescript_spaces_within_interpolation_expressions = false +ij_typescript_spaces_within_method_call_parentheses = false +ij_typescript_spaces_within_method_parentheses = false +ij_typescript_spaces_within_object_literal_braces = true +ij_typescript_spaces_within_object_type_braces = true +ij_typescript_spaces_within_parentheses = false +ij_typescript_spaces_within_switch_parentheses = false +ij_typescript_spaces_within_type_assertion = false +ij_typescript_spaces_within_union_types = true +ij_typescript_spaces_within_while_parentheses = false +ij_typescript_special_else_if_treatment = true +ij_typescript_ternary_operation_signs_on_next_line = false +ij_typescript_ternary_operation_wrap = off +ij_typescript_union_types_wrap = on_every_item +ij_typescript_use_chained_calls_group_indents = false +ij_typescript_use_double_quotes = false +ij_typescript_use_explicit_js_extension = global +ij_typescript_use_path_mapping = always +ij_typescript_use_public_modifier = false +ij_typescript_use_semicolon_after_statement = true +ij_typescript_var_declaration_wrap = normal +ij_typescript_while_brace_force = never +ij_typescript_while_on_new_line = false +ij_typescript_wrap_comments = true diff --git a/package.json b/package.json index 94f3719..85ce2fb 100755 --- a/package.json +++ b/package.json @@ -36,54 +36,54 @@ }, "homepage": "https://github.com/nonara/ts-patch#readme", "dependencies": { - "chalk": "^2.4.2", + "chalk": "^3.0.0", "global-prefix": "^3.0.0", "minimist": "^1.2.0", "shelljs": "^0.8.3", - "strip-ansi": "^5.2.0" + "strip-ansi": "^6.0.0" }, "bin": { "ts-patch": "./dist/bin/cli.js" }, "peerDependencies": { - "typescript": ">2.7.0" + "typescript": ">3.7.2" }, "devDependencies": { - "@phenomnomnominal/tsquery": "^3.0.0", - "@types/chai": "^4.2.4", - "@types/expect": "^1.20.4", + "@phenomnomnominal/tsquery": "^4.0.0", + "@types/chai": "^4.2.5", + "@types/expect": "^24.3.0", "@types/istanbul": "^0.4.30", "@types/minimist": "^1.2.0", "@types/mocha": "^5.2.7", "@types/resolve": "0.0.8", "@types/rewire": "^2.5.28", - "@types/shelljs": "^0.8.5", + "@types/shelljs": "^0.8.6", "@types/sinon-chai": "^3.2.3", "@types/test-console": "^1.1.0", "chai": "^4.2.0", - "coveralls": "^3.0.7", - "graphql": "^14.0.2", - "graphql-tag": "^2.10.0", + "coveralls": "^3.0.9", + "graphql": "^14.5.8", + "graphql-tag": "^2.10.1", "mocha": "^6.2.2", "nyc": "^14.1.1", "rewire": "^4.0.1", "rimraf": "^3.0.0", - "rollup": "1.25.2", - "rollup-plugin-dts": "^1.1.10", - "rollup-plugin-typescript2": "^0.24.3", + "rollup": "^1.27.5", + "rollup-plugin-dts": "^1.1.12", + "rollup-plugin-typescript2": "^0.25.2", "sinon": "^7.5.0", "sinon-chai": "^3.3.0", "source-map-support": "^0.5.16", "test-console": "^1.1.0", - "ts-nameof": "^2.0.0", - "ts-node": "^8.4.1", + "ts-nameof": "^4.2.0", + "ts-node": "^8.5.4", "ts-transform-css-modules": "^0.3.3", "ts-transform-graphql-tag": "^0.2.1", - "ts-transform-img": "^0.3.2", - "ts-transform-react-intl": "^0.4.0", - "ts-transformer-enumerate": "^0.3.1", - "ts-transformer-keys": "^0.3.4", - "typescript": "^3.6.4" + "ts-transform-img": "^0.4.2", + "ts-transform-react-intl": "^0.4.1", + "ts-transformer-enumerate": "^0.5.1", + "ts-transformer-keys": "^0.4.1", + "typescript": "^3.7.2" }, "directories": { "resources": "./dist/resources" diff --git a/rollup.config.js b/rollup.config.js index 381aeda..86f5953 100755 --- a/rollup.config.js +++ b/rollup.config.js @@ -16,18 +16,18 @@ const tsOptions = { const config = [ { input: 'src/patch/main.ts', - output: [{ - file: path.join(pkg.directories.resources, 'module-patch.js'), - format: 'iife', - globals: [ 'ts' ] - }], + output: [ { + file: path.join(pkg.directories.resources, 'module-patch.js'), + format: 'iife', + globals: [ 'ts' ] + } ], plugins: [ typescript(tsOptions) ] }, { input: 'src/patch/types.ts', - output: [{ + output: [ { file: path.join(pkg.directories.resources, 'module-patch.d.ts') - }], + } ], plugins: [ dts(), buildPatchTypes() ] } ]; diff --git a/scripts/build-patch-types.js b/scripts/build-patch-types.js index a5f4f46..ecc5de5 100755 --- a/scripts/build-patch-types.js +++ b/scripts/build-patch-types.js @@ -18,9 +18,9 @@ export default function buildPatchTypes() { ); return omit - // Remove selected nodes from final source + // Remove selected nodes from final source .reduce( - (p, {end}, i) => p.concat(code.slice(end, ((i + 1) < omit.length) ? omit[i + 1].pos : void 0)), + (p, { end }, i) => p.concat(code.slice(end, ((i + 1) < omit.length) ? omit[i + 1].pos : void 0)), code.slice(0, omit[0].pos) ) // Format for ambient context (remove 'declare') diff --git a/src/bin/cli.ts b/src/bin/cli.ts index 405f4b8..467d82d 100755 --- a/src/bin/cli.ts +++ b/src/bin/cli.ts @@ -2,7 +2,7 @@ import minimist from 'minimist'; import chalk from 'chalk'; import stripAnsi from 'strip-ansi'; import * as actions from '../lib/actions' -import { parseOptions, Log, TSPOptions, appOptions, tspPackageJSON } from '../lib/system'; +import { appOptions, Log, parseOptions, TSPOptions, tspPackageJSON } from '../lib/system'; import { getTSPackage } from '..'; @@ -13,28 +13,32 @@ import { getTSPackage } from '..'; type MenuData = Record; -const cliOptions:MenuData = { +const cliOptions: MenuData = { silent: { short: 's', caption: 'Run silently' }, global: { short: 'g', caption: 'Target global TypeScript installation' }, verbose: { short: 'v', caption: 'Chat it up' }, basedir: { short: 'd', paramCaption: '', caption: 'Base directory to resolve package from' }, - persist: { caption: + persist: { + caption: 'Enable automatic persistence. (If TypeScript is updated/reinstalled, it will automatically re-patch)' }, 'no-persist': { caption: 'Disable automatic persistence.' }, color: { inverse: true, caption: 'Strip ansi colours from output' } }; -const cliCommands:MenuData = { +const cliCommands: MenuData = { install: { short: 'i', caption: `Installs ts-patch` }, uninstall: { short: 'u', caption: 'Restores original typescript files' }, - check: { short: 'c', caption: + check: { + short: 'c', caption: `Check patch status (use with ${chalk.cyanBright('--basedir')} to specify TS package location)` }, - patch: { short: void 0, paramCaption: ' | ', caption: + patch: { + short: void 0, paramCaption: ' | ', caption: 'Patch specific module(s) ' + chalk.yellow('(Not recommended. Use install instead)') }, - unpatch: { short: void 0, paramCaption: ' | ', caption: + unpatch: { + short: void 0, paramCaption: ' | ', caption: 'Un-patch specific module(s) ' + chalk.yellow('(Not recommended. Use uninstall instead)') }, version: { short: 'v', caption: 'Show version' }, @@ -64,14 +68,14 @@ const menuText = // Commands Object .entries(cliCommands) - .map(([cmd, {short, caption, paramCaption}]) => formatLine([cmd, short], caption, paramCaption)) + .map(([ cmd, { short, caption, paramCaption } ]) => formatLine([ cmd, short ], caption, paramCaption)) .join(LINE_INDENT) + // Options '\r\n' + LINE_INDENT + chalk.bold('Options') + LINE_INDENT + Object .entries(cliOptions) - .map(([long, {short, inverse, caption, paramCaption}]) => formatLine([ + .map(([ long, { short, inverse, caption, paramCaption } ]) => formatLine([ short && `${chalk.cyanBright('-' + short)}`, long && `${chalk.cyanBright(`${inverse ? '--no-' : '--'}${long}`)}` ], caption, paramCaption)) @@ -92,17 +96,17 @@ if (instanceIsCLI) run(); export function run() { let args = minimist(instanceIsCLI ? process.argv.slice(2) : arguments[0].split(' ')); - let cmd:string | undefined = args._[0] ? args._[0].toLowerCase() : void 0; + let cmd: string | undefined = args._[0] ? args._[0].toLowerCase() : void 0; try { /* Select command by short or full code */ if (cmd) cmd = (Object.keys(cliCommands).includes(cmd)) ? cmd : - (Object.entries(cliCommands).find(([n, {short}]) => n && (short == cmd)) || [])[0]; + (Object.entries(cliCommands).find(([ n, { short } ]) => n && (short == cmd)) || [])[0]; /* Parse options (convert short-code to long) */ const opts = Object .entries(cliOptions) - .reduce((p, [key, {short}]) => ({ + .reduce((p, [ key, { short } ]) => ({ ...p, ...(args.hasOwnProperty(key) && { [key]: args[key] }), ...(short && args.hasOwnProperty(short) && { [key]: args[short] }) @@ -119,34 +123,42 @@ export function run() { /* Handle commands */ (() => { switch (cmd) { - case 'help': return Log(menuText, Log.system); + case 'help': + return Log(menuText, Log.system); case 'version': - const {version: tsVersion, packageDir} = getTSPackage(appOptions.basedir); + const { version: tsVersion, packageDir } = getTSPackage(appOptions.basedir); return Log('\r\n' + chalk.bold.blue('ts-patch: ') + tspPackageJSON.version + '\r\n' + chalk.bold.blue('typescript: ') + tsVersion + chalk.gray(` [${packageDir}]`), Log.system ); - case 'install': return actions.install(); + case 'install': + return actions.install(); - case 'uninstall': return actions.uninstall(); + case 'uninstall': + return actions.uninstall(); - case 'patch': return actions.patch(args._.slice(1).join(' ')); + case 'patch': + return actions.patch(args._.slice(1).join(' ')); - case 'unpatch': return actions.unpatch(args._.slice(1).join(' ')); + case 'unpatch': + return actions.unpatch(args._.slice(1).join(' ')); - case 'check': return actions.check(); + case 'check': + return actions.check(); - default: return (args.persist === undefined) ? - Log('Invalid command. Try ts-patch /? for more info', Log.system) : {} + default: + return (args.persist === undefined) ? + Log('Invalid command. Try ts-patch /? for more info', Log.system) : {} } })(); /* Handle persist option */ if (args.persist !== undefined) (args.persist) ? actions.enablePersistence() : actions.disablePersistence(); - } catch (e) { + } + catch (e) { Log([ '!', chalk.bold.yellow(e.name && (e.name !== 'Error') ? `[${e.name}]: ` : 'Error: ') + chalk.red(e.message) @@ -154,7 +166,7 @@ export function run() { } // Output for analysis by tests - return (!instanceIsCLI) ? ({cmd, args, options: appOptions}) : void 0; + return (!instanceIsCLI) ? ({ cmd, args, options: appOptions }) : void 0; } -// endregion \ No newline at end of file +// endregion diff --git a/src/bin/persist.ts b/src/bin/persist.ts index 62eba6d..294040f 100755 --- a/src/bin/persist.ts +++ b/src/bin/persist.ts @@ -2,8 +2,7 @@ import path from 'path'; import fs from 'fs'; -import { getTSPackage } from '..'; -import { patch } from '..'; +import { getTSPackage, patch } from '..'; /* ******************************************************************************************************************** @@ -11,12 +10,12 @@ import { patch } from '..'; * ********************************************************************************************************************/ /* Read config file */ -const {config, libDir, packageDir} = getTSPackage(path.resolve(path.dirname(process.argv[1]), '../../')); +const { config, libDir, packageDir } = getTSPackage(path.resolve(path.dirname(process.argv[1]), '../../')); if (!config.persist) process.exit(); /* Iterate and patch updated files */ -for (let [filename, timestamp] of Object.entries(config.modules)) { +for (let [ filename, timestamp ] of Object.entries(config.modules)) { const file = path.join(libDir, filename); if (timestamp < fs.statSync(file).mtimeMs) { try { patch(file, { silent: true, basedir: packageDir }) } diff --git a/src/lib/actions.ts b/src/lib/actions.ts index 75dbdd2..dd81590 100755 --- a/src/lib/actions.ts +++ b/src/lib/actions.ts @@ -17,14 +17,14 @@ import resolve = require('resolve'); * ********************************************************************************************************************/ // region Config -export const tsDependencies = ['ts-node', 'resolve']; +export const tsDependencies = [ 'ts-node', 'resolve' ]; shell.config.silent = true; -export const SRC_FILES = ['tsc.js', 'tsserverlibrary.js', 'typescript.js', 'typescriptServices.js']; +export const SRC_FILES = [ 'tsc.js', 'tsserverlibrary.js', 'typescript.js', 'typescriptServices.js' ]; export const BACKUP_DIRNAME = 'lib-backup'; export const RESOURCES_PATH = path.join(appRoot, tspPackageJSON.directories.resources); -export const HOOKS_FILES = ['postinstall', 'postinstall.cmd']; +export const HOOKS_FILES = [ 'postinstall', 'postinstall.cmd' ]; // endregion @@ -40,8 +40,8 @@ export const HOOKS_FILES = ['postinstall', 'postinstall.cmd']; export function parseFiles(fileOrFilesOrGlob: string | string[], dir: string, includeSrc: boolean = false) { const files = Array.isArray(fileOrFilesOrGlob) ? fileOrFilesOrGlob : - fs.existsSync(getModuleAbsolutePath(fileOrFilesOrGlob, dir)) ? [fileOrFilesOrGlob] : - glob.sync(fileOrFilesOrGlob); + fs.existsSync(getModuleAbsolutePath(fileOrFilesOrGlob, dir)) ? [ fileOrFilesOrGlob ] : + glob.sync(fileOrFilesOrGlob); const ret = files.map(f => getTSModule(getModuleAbsolutePath(f, dir), includeSrc)); @@ -74,7 +74,7 @@ function backup(tsModule: TSModule, tsPackage: TSPackage) { */ function restore(currentModule: TSModule, tsPackage: TSPackage) { const backupDir = path.join(tsPackage.packageDir, BACKUP_DIRNAME); - const {file, filename, canPatch, patchVersion, dir} = getTSModule(path.join(backupDir, currentModule.filename)); + const { file, filename, canPatch, patchVersion, dir } = getTSModule(path.join(backupDir, currentModule.filename)); /* Verify backup file */ if (!canPatch) throw new RestoreError(filename, `Backup file is not a valid typescript module!`); @@ -99,7 +99,7 @@ function restore(currentModule: TSModule, tsPackage: TSPackage) { // Remove backup dir if empty if ((fs.readdirSync(backupDir).length < 1) && shell.rm('-rf', backupDir) && shell.error()) - Log(['!', `Error deleting backup directory` + chalk.grey(`[${backupDir}]`)], Log.verbose); + Log([ '!', `Error deleting backup directory` + chalk.grey(`[${backupDir}]`) ], Log.verbose); } /** @@ -109,12 +109,13 @@ function removeDependencies(tsPackage: TSPackage) { const pkgFile = path.join(tsPackage.packageDir, 'package.json'); try { - const pkgData:any = JSON.parse(fs.readFileSync(pkgFile, 'utf8')); + const pkgData: any = JSON.parse(fs.readFileSync(pkgFile, 'utf8')); for (const d of tsDependencies) delete pkgData.dependencies[d]; fs.writeFileSync(pkgFile, JSON.stringify(pkgData, null, 2)); - } catch (e) { + } + catch (e) { throw new PatchError(e.message); } } @@ -126,7 +127,7 @@ function installDependencies(tsPackage: TSPackage) { const pkgFile = path.join(tsPackage.packageDir, 'package.json'); /* Read TS package json */ - let pkgData:any; + let pkgData: any; try { pkgData = JSON.parse(fs.readFileSync(pkgFile, 'utf8')); } catch (e) { throw new PatchError(e.message); } @@ -139,15 +140,16 @@ function installDependencies(tsPackage: TSPackage) { try { location = resolve.sync(`${name}/package.json`, { basedir: tsPackage.packageDir }); version = require(location).version; - } catch (e) { } + } + catch (e) { } return ({ name, location, version }) }); /* Install missing dependencies */ - const missingDeps = getDependenciesDetail().filter(({version}) => !version); + const missingDeps = getDependenciesDetail().filter(({ version }) => !version); if (missingDeps.length > 0) { - Log(['~', `Installing dependencies: ${missingDeps.map(({name}) => name).join(', ')} (via npm)...`], Log.verbose); + Log([ '~', `Installing dependencies: ${missingDeps.map(({ name }) => name).join(', ')} (via npm)...` ], Log.verbose); /* * Note: The environment variable is used here to compensate for an issue within istanbuljs/spawn-wrap @@ -157,12 +159,12 @@ function installDependencies(tsPackage: TSPackage) { * This workaround will be replaced shortly. */ shell.exec( - `npm i --no-audit ${ process.platform === 'win32' ? '%PACKAGES%' : '$PACKAGES' }`, + `npm i --no-audit ${process.platform === 'win32' ? '%PACKAGES%' : '$PACKAGES'}`, { cwd: path.resolve(tsPackage.packageDir, '..'), env: { ...process.env, - PACKAGES: missingDeps.map(({name}) => name).join(' ') + PACKAGES: missingDeps.map(({ name }) => name).join(' ') } } ); @@ -171,7 +173,7 @@ function installDependencies(tsPackage: TSPackage) { } /* Write versions to TS dependencies */ - for (const {name, version} of getDependenciesDetail()) pkgData.dependencies[name] = `^${version}`; + for (const { name, version } of getDependenciesDetail()) pkgData.dependencies[name] = `^${version}`; try { fs.writeFileSync(pkgFile, JSON.stringify(pkgData, null, 2)) } catch (e) { throw new PatchError(e.message) } @@ -195,7 +197,7 @@ export const setOptions = (opts?: Partial) => resetOptions(opts); */ export function install(opts?: Partial) { const ret = patch(SRC_FILES, opts); - if (ret) Log(['+', chalk.green(`ts-patch installed!`)]); + if (ret) Log([ '+', chalk.green(`ts-patch installed!`) ]); return ret; } @@ -204,7 +206,7 @@ export function install(opts?: Partial) { */ export function uninstall(opts?: Partial) { const ret = unpatch(SRC_FILES, opts); - if (ret) Log(['-', chalk.green(`ts-patch removed!`)]); + if (ret) Log([ '-', chalk.green(`ts-patch removed!`) ]); return ret; } @@ -212,18 +214,18 @@ export function uninstall(opts?: Partial) { * Check if files can be patched */ export function check(fileOrFilesOrGlob: string | string[] = SRC_FILES, opts?: Partial) { - const {basedir} = parseOptions(opts); - const {libDir, packageDir, version} = getTSPackage(basedir); + const { basedir } = parseOptions(opts); + const { libDir, packageDir, version } = getTSPackage(basedir); Log(`Checking TypeScript ${chalk.blueBright(`v${version}`)} installation in ${chalk.blueBright(packageDir)}\r\n`); const modules = parseFiles(fileOrFilesOrGlob, libDir); - for (const {filename, patchVersion, canPatch} of modules) { + for (const { filename, patchVersion, canPatch } of modules) { if (patchVersion) Log( - ['+', `${chalk.blueBright(filename)} is patched with ts-patch version ${chalk.blueBright(patchVersion)}.`] + [ '+', `${chalk.blueBright(filename)} is patched with ts-patch version ${chalk.blueBright(patchVersion)}.` ] ); - else if (canPatch) Log(['-', `${chalk.blueBright(filename)} is not patched.`]); - else Log(['-', chalk.red(`${chalk.redBright(filename)} is not patched and cannot be patched!`)]); + else if (canPatch) Log([ '-', `${chalk.blueBright(filename)} is not patched.` ]); + else Log([ '-', chalk.red(`${chalk.redBright(filename)} is not patched and cannot be patched!`) ]); Log('', Log.verbose); } @@ -236,33 +238,33 @@ export function check(fileOrFilesOrGlob: string | string[] = SRC_FILES, opts?: P */ export function patch(fileOrFilesOrGlob: string | string[], opts?: Partial) { if (!fileOrFilesOrGlob) throw new PatchError(`Must provide a file path, array of files, or glob.`); - const {basedir} = parseOptions(opts); + const { basedir } = parseOptions(opts); const tsPackage = getTSPackage(basedir); const modules = parseFiles(fileOrFilesOrGlob, tsPackage.libDir, true); if (modules.alreadyPatched.length >= modules.length) { - Log(['!', `Files already patched. For details, run: `+ chalk.bgBlackBright('ts-patch check')]); + Log([ '!', `Files already patched. For details, run: ` + chalk.bgBlackBright('ts-patch check') ]); return true; } /* Patch files */ for (let m of modules.patchable) { - const {file, filename} = m; - Log(['~', `Patching ${chalk.blueBright(filename)} in ${chalk.blueBright(path.dirname(file))}`], Log.verbose); + const { file, filename } = m; + Log([ '~', `Patching ${chalk.blueBright(filename)} in ${chalk.blueBright(path.dirname(file))}` ], Log.verbose); backup(m, tsPackage); patchTSModule(m, tsPackage); tsPackage.config.modules[filename] = fs.statSync(file).mtimeMs; - Log(['+', chalk.green(`Successfully patched ${chalk.bold.yellow(filename)}.\r\n`)], Log.verbose); + Log([ '+', chalk.green(`Successfully patched ${chalk.bold.yellow(filename)}.\r\n`) ], Log.verbose); } tsPackage.config.save(); installDependencies(tsPackage); if (modules.unPatchable.length > 1) { - Log(['!', + Log([ '!', `Some files can't be patched! Try updating to a newer version of ts-patch. The following files are unable to be ` + `patched. [${modules.unPatchable.map(f => f.filename).join(', ')}]` ]); @@ -274,28 +276,29 @@ export function patch(fileOrFilesOrGlob: string | string[], opts?: Partial) { if (!fileOrFilesOrGlob) throw new PatchError(`Must provide a file path, array of files, or glob.`); - const {basedir, verbose, instanceIsCLI} = parseOptions(opts); + const { basedir, verbose, instanceIsCLI } = parseOptions(opts); const tsPackage = getTSPackage(basedir); const modules = parseFiles(fileOrFilesOrGlob, tsPackage.libDir, true); if (modules.alreadyPatched.length < 1) { - Log(['!', `No patched files detected. For details, run: `+ chalk.bgBlackBright('ts-patch check')]); + Log([ '!', `No patched files detected. For details, run: ` + chalk.bgBlackBright('ts-patch check') ]); return false; } /* Restore files */ const errors: Record = {}; for (let tsModule of modules.alreadyPatched) { - const {file, filename} = tsModule; - Log(['~', `Restoring ${chalk.blueBright(filename)} in ${chalk.blueBright(path.dirname(file))}`], Log.verbose); + const { file, filename } = tsModule; + Log([ '~', `Restoring ${chalk.blueBright(filename)} in ${chalk.blueBright(path.dirname(file))}` ], Log.verbose); try { restore(tsModule, tsPackage); delete tsPackage.config.modules[filename]; - Log(['+', chalk.green(`Successfully restored ${chalk.bold.yellow(filename)}.\r\n`)], Log.verbose); - } catch (e) { + Log([ '+', chalk.green(`Successfully restored ${chalk.bold.yellow(filename)}.\r\n`) ], Log.verbose); + } + catch (e) { errors[filename] = e; } } @@ -314,7 +317,7 @@ export function unpatch(fileOrFilesOrGlob: string | string[], opts?: Partial 0) { Object.values(errors).forEach(e => { if (!instanceIsCLI) console.warn(e); - else Log(['!', e.message], Log.verbose) + else Log([ '!', e.message ], Log.verbose) }); Log(''); @@ -335,7 +338,7 @@ export function enablePersistence(opts?: Partial) { const { basedir } = parseOptions(opts); const { config, packageDir } = getTSPackage(basedir); - Log(['~', `Enabling persistence in ${chalk.blueBright(packageDir)}`], Log.verbose); + Log([ '~', `Enabling persistence in ${chalk.blueBright(packageDir)}` ], Log.verbose); config.persist = true; config.save(); @@ -367,17 +370,17 @@ export function enablePersistence(opts?: Partial) { throw new PersistenceError(`Error writing to hooks file '${path.basename(file)}': ${shell.error()}`); } - Log(['+', chalk.green(`Enabled persistence for ${chalk.blueBright(packageDir)}`)]); + Log([ '+', chalk.green(`Enabled persistence for ${chalk.blueBright(packageDir)}`) ]); } /** * Disable persistence hooks */ export function disablePersistence(opts?: Partial) { - const {basedir} = parseOptions(opts); - const {config, packageDir} = getTSPackage(basedir); + const { basedir } = parseOptions(opts); + const { config, packageDir } = getTSPackage(basedir); - Log(['~', `Disabling persistence in ${chalk.blueBright(packageDir)}`], Log.verbose); + Log([ '~', `Disabling persistence in ${chalk.blueBright(packageDir)}` ], Log.verbose); config.persist = false; config.save(); @@ -389,7 +392,7 @@ export function disablePersistence(opts?: Partial) { if (shell.rm('-rf', hooksFiles) && shell.error()) throw new PersistenceError(`Error trying to remove persistence hooks: ${shell.error()}`); - Log(['-', chalk.green(`Disabled persistence for ${chalk.blueBright(packageDir)}`)]); + Log([ '-', chalk.green(`Disabled persistence for ${chalk.blueBright(packageDir)}`) ]); } // endregion \ No newline at end of file diff --git a/src/lib/file-utils.ts b/src/lib/file-utils.ts index 2fc5887..418623c 100755 --- a/src/lib/file-utils.ts +++ b/src/lib/file-utils.ts @@ -1,9 +1,9 @@ -import path from "path"; -import fs from "fs"; -import resolve = require('resolve'); +import path from 'path'; +import fs from 'fs'; import { - FileNotFound, PackageError, isAbsolute, Log, appOptions, defineProperties, FileWriteError, tspPackageJSON + appOptions, defineProperties, FileNotFound, FileWriteError, isAbsolute, Log, PackageError, tspPackageJSON } from './system'; +import resolve = require('resolve'); /* ******************************************************************************************************************** @@ -17,7 +17,13 @@ import { export const getGlobalTSDir = () => { const errors = []; const basedir = require('global-prefix'); - const check = (dir: string) => { try { return getTSPackage(dir) } catch (e) { errors.push(e); return {}; } }; + const check = (dir: string) => { + try { return getTSPackage(dir) } + catch (e) { + errors.push(e); + return {}; + } + }; const { packageDir } = (check(basedir) || check(path.join(basedir, 'lib'))); @@ -45,9 +51,16 @@ export const mkdirIfNotExist = (dir: string) => !fs.existsSync(dir) && fs.mkdirS /* ******************************************************************************************************************** * TS Package * ********************************************************************************************************************/ + // region TS Package -export interface TSPackage { version: string, packageFile: string, packageDir: string, config: TSPConfig, libDir: string } +export interface TSPackage { + version: string, + packageFile: string, + packageDir: string, + config: TSPConfig, + libDir: string +} /** * Get TypeScript package info - Resolve from basedir, throws if not cannot find TS package @@ -59,11 +72,12 @@ export function getTSPackage(basedir: string = process.cwd()): TSPackage { if (!packageDir) throw new PackageError(`Could not find typescript package in ${packageDir}`); /* Parse package.json data */ - const packageFile = path.join(packageDir,'package.json'); - const {name, version} = (() => { + const packageFile = path.join(packageDir, 'package.json'); + const { name, version } = (() => { try { return JSON.parse(fs.readFileSync(packageFile, 'utf8')); - } catch (e) { + } + catch (e) { throw new PackageError(`Could not parse json data in ${packageFile}`); } })(); @@ -72,7 +86,7 @@ export function getTSPackage(basedir: string = process.cwd()): TSPackage { if (name !== 'typescript') throw new PackageError(`The package in ${packageDir} is not TypeScript. Found: ${name}.`); - return {version, packageFile, packageDir, config: getConfig(packageDir), libDir: path.join(packageDir, 'lib')}; + return { version, packageFile, packageDir, config: getConfig(packageDir), libDir: path.join(packageDir, 'lib') }; } // endregion @@ -81,6 +95,7 @@ export function getTSPackage(basedir: string = process.cwd()): TSPackage { /* ******************************************************************************************************************** * TS Module * ********************************************************************************************************************/ + // region TS Module export interface TSModule { @@ -95,8 +110,7 @@ export interface TSModule { /** * Get TypeScript module info */ -export function getTSModule(file: string, includeSrc: boolean = false): TSModule -{ +export function getTSModule(file: string, includeSrc: boolean = false): TSModule { if (!fs.existsSync(file)) throw new FileNotFound(`Could not find file ${file}.`); const filename = path.basename(file); @@ -107,7 +121,7 @@ export function getTSModule(file: string, includeSrc: boolean = false): TSModule canPatch && (fileData.match(/(?<=^\s*?var\stspVersion\s?=\s?['"`])(\S+?)(?=['"`])/m) || [])[0]; - return { file, filename, canPatch, dir, patchVersion, ...(includeSrc && canPatch && {moduleSrc: fileData}) }; + return { file, filename, canPatch, dir, patchVersion, ...(includeSrc && canPatch && { moduleSrc: fileData }) }; } // endregion @@ -116,13 +130,14 @@ export function getTSModule(file: string, includeSrc: boolean = false): TSModule /* ******************************************************************************************************************** * TSP Config * ********************************************************************************************************************/ + // region TSP Config export interface TSPConfig { readonly file: string, readonly version: string, persist: boolean, - modules: { [x:string]: number } + modules: { [x: string]: number } save: Function; } @@ -138,13 +153,14 @@ function getConfig(packageDir: string) { if (fs.existsSync(configFile)) { try { fileData = JSON.parse(fs.readFileSync(configFile, 'utf8')); - } catch (e) { + } + catch (e) { if (appOptions.instanceIsCLI) console.warn(e); - else Log(['!', e.message], Log.verbose) + else Log([ '!', e.message ], Log.verbose) } } - const config:TSPConfig = { + const config: TSPConfig = { persist: false, modules: {}, ...fileData, @@ -162,7 +178,8 @@ function getConfig(packageDir: string) { function saveConfig(config: TSPConfig) { try { fs.writeFileSync(config.file, JSON.stringify(config, null, 2)); - } catch (e) { + } + catch (e) { throw new FileWriteError(config.file, e.message); } } diff --git a/src/lib/patcher.ts b/src/lib/patcher.ts index e64f057..1f4bc7b 100755 --- a/src/lib/patcher.ts +++ b/src/lib/patcher.ts @@ -1,6 +1,6 @@ import fs from 'fs'; import path from 'path'; -import { FileNotFound, PatchError, FileWriteError, WrongTSVersion, tspPackageJSON, appRoot } from './system'; +import { appRoot, FileNotFound, FileWriteError, PatchError, tspPackageJSON, WrongTSVersion } from './system'; import { getTSModule, TSModule, TSPackage } from './file-utils'; import { BACKUP_DIRNAME } from './actions'; @@ -27,7 +27,7 @@ const generatePatch = (isTSC: boolean) => */ function validate(tsModule?: TSModule, tsPackage?: TSPackage) { if (tsModule) { - const {file, filename, dir, patchVersion, canPatch} = tsModule; + const { file, filename, dir, patchVersion, canPatch } = tsModule; if (!fs.existsSync(file)) throw new FileNotFound(`Could not find module ${filename} in ${dir + path.sep}`); @@ -36,9 +36,9 @@ function validate(tsModule?: TSModule, tsPackage?: TSPackage) { } if (tsPackage) { - const {version} = tsPackage; + const { version } = tsPackage; - const [major, minor] = version.split('.'); + const [ major, minor ] = version.split('.'); if (+major < 3 && +minor < 7) throw new WrongTSVersion(`ts-patch requires TypeScript v2.7 or higher.`); } @@ -70,7 +70,7 @@ export function patchTSModule(tsModule: TSModule, tsPackage: TSPackage) { path.join(tsPackage.packageDir, BACKUP_DIRNAME, 'typescript.js'), path.join(tsPackage.libDir, 'typescript.js') ] - .filter(f => fs.existsSync(f))[0]; + .filter(f => fs.existsSync(f))[0]; /* Expand TSC with full typescript library (splice tsc part on top of typescript.ts code) */ fs.writeFileSync(file, @@ -82,10 +82,10 @@ export function patchTSModule(tsModule: TSModule, tsPackage: TSPackage) { ) ]) ); - } - else + } else fs.appendFileSync(file, patchSrc); - } catch (e) { + } + catch (e) { throw new FileWriteError(filename, e.message); } @@ -96,7 +96,8 @@ export function patchTSModule(tsModule: TSModule, tsPackage: TSPackage) { path.join(dir, 'typescript.d.ts'), '\r\n' + fs.readFileSync(path.resolve(appRoot, tspPackageJSON.directories.resources, 'module-patch.d.ts')) ) - } catch (e) { + } + catch (e) { throw new FileWriteError(filename, e.message); } } \ No newline at end of file diff --git a/src/lib/system/errors.ts b/src/lib/system/errors.ts index 7e2f042..a61b300 100755 --- a/src/lib/system/errors.ts +++ b/src/lib/system/errors.ts @@ -1,32 +1,37 @@ - /* ******************************************************************************************************************** * Errors Classes * ********************************************************************************************************************/ -export class WrongTSVersion extends Error { name = 'WrongTSVersion' } -export class FileNotFound extends Error { name = 'FileNotFound' } -export class PackageError extends Error { name = 'PackageError' } -export class PatchError extends Error { name = 'PatchError' } -export class PersistenceError extends Error { name = 'PersistenceError' } -export class OptionsError extends Error { name = 'OptionsError' } -export class NPMError extends Error { name = 'NPMError' } +export class WrongTSVersion extends Error {name = 'WrongTSVersion'} + +export class FileNotFound extends Error {name = 'FileNotFound'} + +export class PackageError extends Error {name = 'PackageError'} + +export class PatchError extends Error {name = 'PatchError'} + +export class PersistenceError extends Error {name = 'PersistenceError'} + +export class OptionsError extends Error {name = 'OptionsError'} + +export class NPMError extends Error {name = 'NPMError'} export class RestoreError extends Error { constructor(public filename: string, message: string) { - super(`Error restoring: ${filename}${message ? ' - '+message : ''}`); + super(`Error restoring: ${filename}${message ? ' - ' + message : ''}`); this.name = 'RestoreError'; } } export class BackupError extends Error { constructor(public filename: string, message: string) { - super(`Error backing up ${filename}${message ? ' - '+message : ''}`); + super(`Error backing up ${filename}${message ? ' - ' + message : ''}`); this.name = 'BackupError'; } } export class FileWriteError extends Error { - constructor(public filename: string, message:string) { + constructor(public filename: string, message: string) { super(`Error while trying to write to ${filename}${message && `: ${message}`}`); } } diff --git a/src/lib/system/helpers.ts b/src/lib/system/helpers.ts index ccb704e..eab9602 100755 --- a/src/lib/system/helpers.ts +++ b/src/lib/system/helpers.ts @@ -1,5 +1,5 @@ -import path from "path"; -import fs from "fs"; +import path from 'path'; +import fs from 'fs'; /* ******************************************************************************************************************** @@ -34,20 +34,18 @@ export function pick(obj: T, ...keys: K[]): Pick { */ export const getKeys = (obj: T): Array => Object.keys(obj) as Array; -type GetDescriptorType any }> = +type GetDescriptorType any }> = 'value' extends keyof T ? T['value'] : T['get'] extends Function ? ReturnType : T['set'] extends Function ? Parameters[0] : T['initializer'] extends Function ? ReturnType : - never; + never; /** * Fully typed Object.defineProperties */ -export function defineProperties ->(obj: TObj, properties: TProps): - TObj & { [K in keyof TProps]: GetDescriptorType } -{ +export function defineProperties>(obj: TObj, properties: TProps): + TObj & { [K in keyof TProps]: GetDescriptorType } { return Object.defineProperties(obj, properties); } diff --git a/src/lib/system/logger.ts b/src/lib/system/logger.ts index 737c95c..38598d6 100755 --- a/src/lib/system/logger.ts +++ b/src/lib/system/logger.ts @@ -10,22 +10,22 @@ import stripAnsi from 'strip-ansi'; /** * Output log message */ -export function Log(msg: string | [string, string], logLevel: typeof Log[keyof typeof Log] = Log.normal) { +export function Log(msg: string | [ string, string ], logLevel: typeof Log[keyof typeof Log] = Log.normal) { if (logLevel > appOptions.logLevel) return; const { color, instanceIsCLI } = appOptions; /* Handle Icon */ - const printIcon = (icon:string) => chalk.bold.cyanBright(`[${ icon }] `); + const printIcon = (icon: string) => chalk.bold.cyanBright(`[${icon}] `); let icon: string = ''; if (Array.isArray(msg)) { icon = msg[0]; msg = (icon === '!') ? printIcon(chalk.bold.yellow(icon)) + chalk.yellow(msg[1]) : - (icon === '~') ? printIcon(chalk.bold.cyanBright(icon)) + msg[1] : - (icon === '=') ? printIcon(chalk.bold.greenBright(icon)) + msg[1] : - (icon === '+') ? printIcon(chalk.bold.green(icon)) + msg[1] : - (icon === '-') ? printIcon(chalk.bold.white(icon)) + msg[1] : - msg[1]; + (icon === '~') ? printIcon(chalk.bold.cyanBright(icon)) + msg[1] : + (icon === '=') ? printIcon(chalk.bold.greenBright(icon)) + msg[1] : + (icon === '+') ? printIcon(chalk.bold.green(icon)) + msg[1] : + (icon === '-') ? printIcon(chalk.bold.white(icon)) + msg[1] : + msg[1]; } const isError = (icon === '!'); diff --git a/src/lib/system/options.ts b/src/lib/system/options.ts index 8aa4af4..246e2c2 100755 --- a/src/lib/system/options.ts +++ b/src/lib/system/options.ts @@ -19,7 +19,7 @@ export const defaultOptions = { }; /** App-wide options storage */ -export let appOptions = {...defaultOptions}; +export let appOptions = { ...defaultOptions }; /* ******************************************************************************************************************** @@ -41,10 +41,10 @@ export const parseOptions = (options?: Partial): TSPOptions => { Object.assign(appOptions, pick(options, ...getKeys(defaultOptions))); appOptions.logLevel = - (appOptions.silent) ? Log.system : - (appOptions.verbose) ? Log.verbose : - (appOptions.instanceIsCLI) ? Log.normal : - defaultOptions.logLevel; + (appOptions.silent) ? Log.system : + (appOptions.verbose) ? Log.verbose : + (appOptions.instanceIsCLI) ? Log.normal : + defaultOptions.logLevel; return appOptions; }; diff --git a/src/patch/createProgram.ts b/src/patch/createProgram.ts index 3e80d66..0da53b0 100755 --- a/src/patch/createProgram.ts +++ b/src/patch/createProgram.ts @@ -143,4 +143,4 @@ export function createProgram( }; return program; -} \ No newline at end of file +} diff --git a/src/patch/plugin.ts b/src/patch/plugin.ts index 17da64b..22f3d6b 100755 --- a/src/patch/plugin.ts +++ b/src/patch/plugin.ts @@ -3,19 +3,20 @@ * Credit & thanks go to cevek (https://github.com/cevek) for the incredible work! */ -import { never } from './shared'; -import { addDiagnosticFactory } from './shared'; +import { addDiagnosticFactory, never } from './shared'; import { - TransformerFactory, SourceFile, Bundle, CustomTransformers, LanguageService, Program, Diagnostic, CompilerOptions, - TypeChecker, TransformationContext, Transformer, default as TS + Bundle, CompilerOptions, CustomTransformers, default as TS, Diagnostic, LanguageService, Program, SourceFile, + TransformationContext, Transformer, TransformerFactory, TypeChecker } from 'typescript'; + declare const ts: typeof TS & { originalCreateProgram: typeof TS.createProgram }; /* ******************************************************************************************************************** * Types * ********************************************************************************************************************/ + // region Types export interface PluginConfig { @@ -116,7 +117,7 @@ export class PluginCreator { } public mergeTransformers(into: TransformerList, source: CustomTransformers | TransformerBasePlugin) { - const slice = (input: T | T[]) => (Array.isArray(input) ? input.slice() : [input]); + const slice = (input: T | T[]) => (Array.isArray(input) ? input.slice() : [ input ]); if (source.before) into.before.push(...slice(source.before)); if (source.after) into.after.push(...slice(source.after)); @@ -131,7 +132,7 @@ export class PluginCreator { ) { const chain: TransformerList = { before: [], after: [], afterDeclarations: [] }; - const [ls, program] = ('ls' in params) ? [params.ls, params.ls.getProgram()!] : [void 0, params.program]; + const [ ls, program ] = ('ls' in params) ? [ params.ls, params.ls.getProgram()! ] : [ void 0, params.program ]; for (const config of this.configs) { if (!config.transform) continue; @@ -184,13 +185,13 @@ export class PluginCreator { if (!factory) throw new Error( `tsconfig.json > plugins: "${transform}" does not have an export "${importKey}": ` + - require("util").inspect(factoryModule) + require('util').inspect(factoryModule) ); if (typeof factory !== 'function') { throw new Error( `tsconfig.json > plugins: "${transform}" export "${importKey}" is not a plugin: ` + - require("util").inspect(factory) + require('util').inspect(factory) ); } @@ -208,8 +209,7 @@ export class PluginCreator { program: Program; ls?: LanguageService; }): - TransformerBasePlugin - { + TransformerBasePlugin { const { transform, after, afterDeclarations, name, type, ...cleanConfig } = config; if (!transform) throw new Error('Not a valid config entry: "transform" key not found'); @@ -251,8 +251,8 @@ export class PluginCreator { if (typeof ret === 'function') return after ? ({ after: ret }) : - afterDeclarations ? ({ afterDeclarations: ret as TransformerFactory }) : - { before: ret }; + afterDeclarations ? ({ afterDeclarations: ret as TransformerFactory }) : + { before: ret }; return ret; } diff --git a/test/actions.test.ts b/test/actions.test.ts index 8f75226..bbf442a 100755 --- a/test/actions.test.ts +++ b/test/actions.test.ts @@ -3,13 +3,13 @@ import fs from 'fs'; import shell from 'shelljs'; import { expect } from 'chai'; import { getTSPackage, install, patch, setOptions, uninstall } from '../src'; -import { - SRC_FILES, BACKUP_DIRNAME, check, parseFiles, enablePersistence, disablePersistence, tsDependencies -} from '../src/lib/actions'; import { backupDir, createTSInstallation, destDir, installFakePackage, installTSPatch, libDir, removeTSInstallation, removeTSPatch, tmpDir } from './lib/helpers'; +import { + BACKUP_DIRNAME, check, disablePersistence, enablePersistence, parseFiles, SRC_FILES, tsDependencies +} from '../src/lib/actions'; import resolve = require('resolve'); @@ -34,8 +34,8 @@ function checkModules( ) { const modules = parseFiles(filenames, dir); expect(modules.map(m => m.filename)).to.eql(filenames); - for (let {canPatch, patchVersion} of modules) - expect({canPatch, patchVersion}).to.eql({ canPatch: true, patchVersion: expectedPatchVersion }); + for (let { canPatch, patchVersion } of modules) + expect({ canPatch, patchVersion }).to.eql({ canPatch: true, patchVersion: expectedPatchVersion }); } const callPatch = (files: any, tsVersion?: string) => { @@ -79,7 +79,7 @@ describe(`Actions (slow, mostly due to npm)`, () => { expect(Object .entries(config.modules) - .filter(([filename, timestamp]) => + .filter(([ filename, timestamp ]) => SRC_FILES.includes(filename) && // Filename must be valid !isNaN(parseFloat(timestamp)) // Timestamp must be valid ) @@ -89,7 +89,7 @@ describe(`Actions (slow, mostly due to npm)`, () => { it(`check() is accurate`, () => { const modules = check(SRC_FILES); - expect(modules.map(({filename}) => filename)).to.eql(SRC_FILES); + expect(modules.map(({ filename }) => filename)).to.eql(SRC_FILES); expect(modules.unPatchable.length).to.eql(0); expect(modules.patchable.length).to.eql(0); expect(modules.alreadyPatched.length).to.eql(SRC_FILES.length); @@ -138,7 +138,7 @@ describe(`Actions (slow, mostly due to npm)`, () => { it(`Patches single file`, () => { callPatch(SRC_FILES[0]); - checkModules(tspVersion, libDir, [SRC_FILES[0]]); + checkModules(tspVersion, libDir, [ SRC_FILES[0] ]); }); it(`Patches array of files`, () => { @@ -147,13 +147,14 @@ describe(`Actions (slow, mostly due to npm)`, () => { }); it(`Patches glob`, () => { - callPatch(path.join(libDir,'*.js')); + callPatch(path.join(libDir, '*.js')); checkModules(tspVersion, libDir); }); it(`Throws with TS version < 2.7`, () => { let err: Error | undefined; - try { callPatch(SRC_FILES, '2.6.0'); } catch (e) { err = e; } + try { callPatch(SRC_FILES, '2.6.0'); } + catch (e) { err = e; } expect(err && err.name).to.eq('WrongTSVersion'); }); }); @@ -198,7 +199,7 @@ describe(`Actions (slow, mostly due to npm)`, () => { expect(modules.patchable.length).to.eq(modules.length); /* Mark one to skip */ - const {config} = getTSPackage(destDir); + const { config } = getTSPackage(destDir); skippedFilename = modules[0].filename; config.modules[skippedFilename] += 5 * (60000); config.save(); @@ -214,7 +215,7 @@ describe(`Actions (slow, mostly due to npm)`, () => { ); it(`Re-patches modules after hook invoked`, () => - expect(modules.alreadyPatched.length >= modules.length-1).to.true + expect(modules.alreadyPatched.length >= modules.length - 1).to.true ); it(`Skips patching non-modified module`, () => { diff --git a/test/cli.test.ts b/test/cli.test.ts index 4435070..973f449 100755 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -27,8 +27,8 @@ const actions = { cliModule.__set__('actions', actions); -const commands:any = cliModule.__get__('cliCommands'); -const options:any = cliModule.__get__('cliOptions'); +const commands: any = cliModule.__get__('cliCommands'); +const options: any = cliModule.__get__('cliOptions'); /* ******************************************************************************************************************** @@ -36,7 +36,10 @@ const options:any = cliModule.__get__('cliOptions'); * ********************************************************************************************************************/ const opts = { color: false }; -const run = (...args:any[]) => { setOptions(opts); return cliModule.run(args.join(' ')) as ReturnType }; +const run = (...args: any[]) => { + setOptions(opts); + return cliModule.run(args.join(' ')) as ReturnType +}; const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); @@ -45,7 +48,7 @@ const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); * ********************************************************************************************************************/ describe(`CLI`, () => { - let logSpy:SinonSpy; + let logSpy: SinonSpy; before(() => logSpy = sinon.stub(console, 'log')); after(() => logSpy.restore()); afterEach(() => logSpy.resetHistory()); @@ -53,17 +56,41 @@ describe(`CLI`, () => { describe(`Action commands run`, () => { afterEach(sinon.resetHistory); - it(`Install`, () => { run('install'); expect(actions['install']).to.be.calledOnce}); - it(`Uninstall`, () => { run('uninstall'); expect(actions['uninstall']).to.be.calledOnce}); - it(`Patch`, () => { run('patch'); expect(actions['patch']).to.be.calledOnce}); - it(`Unpatch`, () => { run('unpatch'); expect(actions['unpatch']).to.be.calledOnce}); - it(`Check`, () => { run('check'); expect(actions['check']).to.be.calledOnce}); - it(`--persist`, () => { run('--persist'); expect(actions['enablePersistence']).to.be.calledOnce}); - it(`--no-persist`, () => { run('--no-persist'); expect(actions['disablePersistence']).to.be.calledOnce}); + it(`Install`, () => { + run('install'); + expect(actions['install']).to.be.calledOnce + }); + it(`Uninstall`, () => { + run('uninstall'); + expect(actions['uninstall']).to.be.calledOnce + }); + it(`Patch`, () => { + run('patch'); + expect(actions['patch']).to.be.calledOnce + }); + it(`Unpatch`, () => { + run('unpatch'); + expect(actions['unpatch']).to.be.calledOnce + }); + it(`Check`, () => { + run('check'); + expect(actions['check']).to.be.calledOnce + }); + it(`--persist`, () => { + run('--persist'); + expect(actions['enablePersistence']).to.be.calledOnce + }); + it(`--no-persist`, () => { + run('--no-persist'); + expect(actions['disablePersistence']).to.be.calledOnce + }); }); describe(`Log commands output`, () => { - it(`Version`, () => { run('version'); expect(/ts-patch:/g.test(logSpy.lastCall.args.join(' '))).to.be.true }); + it(`Version`, () => { + run('version'); + expect(/ts-patch:/g.test(logSpy.lastCall.args.join(' '))).to.be.true + }); it(`Invalid command`, () => { run('notACommand_'); @@ -81,7 +108,7 @@ describe(`CLI`, () => { it(`Header appears`, () => expect(/^\s*ts-patch \[command]/m.test(output)).to.be.true); it(`All commands appear`, () => { - for (let [cmd, {short, caption, paramCaption}] of (Object.entries(commands) as [string, any])) { + for (let [ cmd, { short, caption, paramCaption } ] of (Object.entries(commands) as [ string, any ])) { caption = stripAnsi(caption); paramCaption = stripAnsi(paramCaption); @@ -92,12 +119,12 @@ describe(`CLI`, () => { escape(caption) + `$`; - expect({ [cmd]: new RegExp(regexStr,'m').test(output) }).to.eql({ [cmd]: true }); + expect({ [cmd]: new RegExp(regexStr, 'm').test(output) }).to.eql({ [cmd]: true }); } }); it(`All args appear`, () => { - for (let [arg, {short, caption, paramCaption, inverse}] of (Object.entries(options) as [string, any])) { + for (let [ arg, { short, caption, paramCaption, inverse } ] of (Object.entries(options) as [ string, any ])) { caption = stripAnsi(caption); paramCaption = stripAnsi(paramCaption); if (inverse) arg = `no-${arg}`; @@ -110,7 +137,7 @@ describe(`CLI`, () => { escape(caption) + `$`; - expect({ [arg]: new RegExp(regexStr,'m').test(output) }).to.eql({ [arg]: true }); + expect({ [arg]: new RegExp(regexStr, 'm').test(output) }).to.eql({ [arg]: true }); } }); }); @@ -124,7 +151,10 @@ describe(`CLI`, () => { }); it(`Global`, () => { - const globalTSDir = (() => { try { return getGlobalTSDir(); } catch (e) { return undefined } })(); + const globalTSDir = (() => { + try { return getGlobalTSDir(); } + catch (e) { return undefined } + })(); if (globalTSDir) { expect(run('v', '-g')!.options).to.include({ basedir: globalTSDir }); diff --git a/test/lib/helpers.ts b/test/lib/helpers.ts index c4d223a..00f1713 100755 --- a/test/lib/helpers.ts +++ b/test/lib/helpers.ts @@ -1,10 +1,10 @@ -import path from "path"; -import fs from "fs"; +import path from 'path'; +import fs from 'fs'; import shell from 'shelljs'; import { BACKUP_DIRNAME, SRC_FILES } from '../../src/lib/actions'; import { getModuleAbsolutePath, mkdirIfNotExist } from '../../src/lib/file-utils'; import { appRoot, tspPackageJSON } from '../../src/lib/system'; -import os from "os"; +import os from 'os'; import resolve from 'resolve'; @@ -17,7 +17,7 @@ export const srcDir = path.dirname(resolve.sync('typescript/package.json')); export const destDir = path.join(tmpDir, 'node_modules', 'typescript'); export const libDir = path.join(destDir, 'lib'); export const backupDir = path.join(destDir, BACKUP_DIRNAME); -const fakePkgDir = path.resolve(tmpDir,'fake-pkg'); +const fakePkgDir = path.resolve(tmpDir, 'fake-pkg'); const files = [ ...SRC_FILES.map(f => getModuleAbsolutePath(f, path.join(srcDir, 'lib'))), @@ -43,7 +43,7 @@ export function createTSInstallation(fullInstall: boolean = false, tsVersion?: s /* Setup temp dir */ removeTSInstallation(); - try { mkdirIfNotExist(path.join(destDir,'lib')) } + try { mkdirIfNotExist(path.join(destDir, 'lib')) } catch (e) { throw new Error(`Could not create temp directory! ${e.message}`); } // Write fake module package JSON file @@ -57,7 +57,7 @@ export function createTSInstallation(fullInstall: boolean = false, tsVersion?: s fs.writeFileSync(path.join(destDir, 'package.json'), shell.sed( /(?<="version":\s*?").+?(?=")/, tsVersion!.replace(/[^0-9.\-\w]/g, ''), - path.join(srcDir,'package.json') + path.join(srcDir, 'package.json') )); // Copy relevant typescript files @@ -90,7 +90,7 @@ export function installFakePackage() { fs.writeFileSync(path.join(fakePkgDir, 'package.json'), pkgJSON); // Install package - return shell.exec(`npm i ${fakePkgDir}`, { cwd: tmpDir }); + return shell.exec(`npm i --no-audit ${fakePkgDir}`, { cwd: tmpDir }); } @@ -115,9 +115,9 @@ export function installTSPatch() { throw new Error(`Error copying tsp files. ${shell.error()}`); // Install dependencies - return shell.exec(`npm i`, { cwd: tmpDir }); + shell.exec(`npm i --no-audit`, { cwd: tmpDir }); } export function removeTSPatch() { - return shell.exec(`npm uninstall ts-patch`, { cwd: tmpDir }); + shell.exec(`npm uninstall --no-audit ts-patch`, { cwd: tmpDir }); } \ No newline at end of file diff --git a/test/logger.test.ts b/test/logger.test.ts index be7e365..fccc5c3 100755 --- a/test/logger.test.ts +++ b/test/logger.test.ts @@ -3,7 +3,7 @@ import { setOptions } from '../src'; import chai, { expect } from 'chai'; import sinonChai from 'sinon-chai'; import sinon from 'sinon'; -import { stdout, stderr } from 'test-console'; +import { stderr, stdout } from 'test-console'; chai.use(sinonChai); @@ -12,8 +12,8 @@ chai.use(sinonChai); * Helpers * ********************************************************************************************************************/ -function log(opt?: Partial, msg: string | [string, string] = ['=', 'test']) { - const {instanceIsCLI} = setOptions(opt); +function log(opt?: Partial, msg: string | [ string, string ] = [ '=', 'test' ]) { + const { instanceIsCLI } = setOptions(opt); const logSpy = sinon.stub(console, 'log'); const inspectOut = stdout.inspect(); const inspectErr = stderr.inspect(); @@ -27,15 +27,15 @@ function log(opt?: Partial, msg: string | [string, string] = ['=', ' expect(logSpy).to.not.be.called; if (isError) expect(inspectOut.output.length < 1 && inspectErr.output.length >= 1).to.be.true; else expect(inspectOut.output.length >= 1 && inspectErr.output.length < 1).to.be.true; - } - else expect(inspectOut.output.length < 1 && inspectErr.output.length < 1).to.be.true; + } else expect(inspectOut.output.length < 1 && inspectErr.output.length < 1).to.be.true; return { console: !instanceIsCLI ? logSpy.lastCall.args.join(' ') : '', stderr: inspectErr.output.toString(), stdout: inspectOut.output.toString() }; - } finally { + } + finally { logSpy.restore(); inspectOut.restore(); inspectErr.restore(); @@ -57,10 +57,10 @@ describe(`Logger`, () => { describe(`CLI Mode`, () => { it(`Log goes to stdout`, () => - expect(/std_out/g.test(log({ instanceIsCLI: true },['=','std_out']).stdout)).to.be.true + expect(/std_out/g.test(log({ instanceIsCLI: true }, [ '=', 'std_out' ]).stdout)).to.be.true ); it(`Error goes to stderr`, () => - expect(/std_err/g.test(log({ instanceIsCLI: true },['!','std_err']).stderr)).to.be.true + expect(/std_err/g.test(log({ instanceIsCLI: true }, [ '!', 'std_err' ]).stderr)).to.be.true ); }); -}); \ No newline at end of file +}); diff --git a/test/patch/tests/PluginCreator.ts b/test/patch/tests/PluginCreator.ts index ef55f4d..b83bb8c 100755 --- a/test/patch/tests/PluginCreator.ts +++ b/test/patch/tests/PluginCreator.ts @@ -39,7 +39,7 @@ export default function suite() { expect(createTransformers(config)).to.eql({ after: [], afterDeclarations: [], - before: [simpleTransformer], + before: [ simpleTransformer ], }); }); @@ -47,7 +47,7 @@ export default function suite() { const config: PluginConfig[] = [ { transform: '../transforms/transform-simple.ts', after: true } ]; expect(createTransformers(config)).to.eql({ - after: [simpleTransformer], + after: [ simpleTransformer ], afterDeclarations: [], before: [], }); @@ -57,17 +57,17 @@ export default function suite() { const config: PluginConfig[] = [ { transform: '../transforms/transform-advanced.ts' } ]; expect(createTransformers(config)).to.eql({ - after: [advancedTransformer], + after: [ advancedTransformer ], afterDeclarations: [], before: [], }); }); it('should provide custom config', () => { - const config: PluginConfig[] = [{ transform: '../transforms/transform-advanced.ts', some: 1, bla: 2 } as any]; + const config: PluginConfig[] = [ { transform: '../transforms/transform-advanced.ts', some: 1, bla: 2 } as any ]; expect(createTransformers(config)).to.eql({ - after: [advancedTransformer], + after: [ advancedTransformer ], afterDeclarations: [], before: [], }); diff --git a/test/patch/tests/typescript.ts b/test/patch/tests/typescript.ts index b5fa105..874a814 100755 --- a/test/patch/tests/typescript.ts +++ b/test/patch/tests/typescript.ts @@ -29,9 +29,9 @@ export default function suite() { it('Applies transformer from legacy config', () => { const res = ts.transpileModule(safelyCode, { compilerOptions: { - plugins: [{ - customTransformers: { before: [path.join(__dirname, '../transforms/safely.ts')] }, - }] as any, + plugins: [ { + customTransformers: { before: [ path.join(__dirname, '../transforms/safely.ts') ] }, + } ] as any, }, }); @@ -41,9 +41,9 @@ export default function suite() { it('Applies transformer from default config', () => { const res = ts.transpileModule(safelyCode, { compilerOptions: { - plugins: [{ + plugins: [ { transform: path.join(__dirname, '../transforms/safely.ts'), - }] as any, + } ] as any, }, }); @@ -51,15 +51,15 @@ export default function suite() { }); it('Merges transformers', () => { - const customTransformer = sinon.spy((sf:any) => sf); + const customTransformer = sinon.spy((sf: any) => sf); const res = ts.transpileModule(safelyCode, { compilerOptions: { - plugins: [{ + plugins: [ { transform: path.join(__dirname, '../transforms/safely.ts'), - }] as any, + } ] as any, }, - transformers: { before: [() => customTransformer] }, + transformers: { before: [ () => customTransformer ] }, }); expect(res.outputText).to.match(safelyExpected); @@ -87,9 +87,9 @@ export default function suite() { it('Skips ts plugin without errors', () => { const res = ts.transpileModule(basicCode, { compilerOptions: { - plugins: [{ name: 'foobar' }], + plugins: [ { name: 'foobar' } ], }, }); expect(res.outputText).to.match(basicExpected) }); -} \ No newline at end of file +} diff --git a/tsconfig.json b/tsconfig.json index 03cef27..efa1dce 100755 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,4 +22,4 @@ "rootDirs": ["src", "dist"] } -} \ No newline at end of file +}