jsii-rosetta 1.76.0 → 4.9.0-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +1 -0
- package/README.md +287 -388
- package/bin/jsii-rosetta +1 -1
- package/lib/ambient/semver-intersect.d.ts +13 -0
- package/lib/ambient/semver-intersect.js +2 -0
- package/lib/ambient/semver-intersect.js.map +1 -0
- package/lib/commands/convert.js.map +1 -0
- package/lib/commands/coverage.js.map +1 -0
- package/lib/commands/extract.js +2 -2
- package/lib/commands/extract.js.map +1 -0
- package/lib/commands/infuse.js +2 -2
- package/lib/commands/infuse.js.map +1 -0
- package/lib/commands/read.js +6 -6
- package/lib/commands/read.js.map +1 -0
- package/lib/commands/transliterate.js +4 -4
- package/lib/commands/transliterate.js.map +1 -0
- package/lib/commands/trim-cache.js.map +1 -0
- package/lib/find-utils.js +4 -4
- package/lib/find-utils.js.map +1 -0
- package/lib/fixtures.js +2 -2
- package/lib/fixtures.js.map +1 -0
- package/lib/index.js.map +1 -0
- package/lib/jsii/assemblies.d.ts +1 -1
- package/lib/jsii/assemblies.js +14 -11
- package/lib/jsii/assemblies.js.map +1 -0
- package/lib/jsii/fingerprinting.js +9 -9
- package/lib/jsii/fingerprinting.js.map +1 -0
- package/lib/jsii/jsii-types.d.ts +4 -4
- package/lib/jsii/jsii-types.js +9 -4
- package/lib/jsii/jsii-types.js.map +1 -0
- package/lib/jsii/jsii-utils.d.ts +1 -1
- package/lib/jsii/jsii-utils.js +2 -2
- package/lib/jsii/jsii-utils.js.map +1 -0
- package/lib/jsii/packages.js.map +1 -0
- package/lib/languages/csharp.d.ts +3 -3
- package/lib/languages/csharp.js +2 -2
- package/lib/languages/csharp.js.map +1 -0
- package/lib/languages/default.d.ts +2 -2
- package/lib/languages/default.js.map +1 -0
- package/lib/languages/go.d.ts +3 -3
- package/lib/languages/go.js +20 -16
- package/lib/languages/go.js.map +1 -0
- package/lib/languages/index.d.ts +1 -1
- package/lib/languages/index.js +4 -4
- package/lib/languages/index.js.map +1 -0
- package/lib/languages/java.d.ts +2 -2
- package/lib/languages/java.js +2 -2
- package/lib/languages/java.js.map +1 -0
- package/lib/languages/python.d.ts +3 -3
- package/lib/languages/python.js +1 -1
- package/lib/languages/python.js.map +1 -0
- package/lib/languages/record-references-version.d.ts +2 -0
- package/lib/languages/record-references-version.js +6 -0
- package/lib/languages/record-references-version.js.map +1 -0
- package/lib/languages/record-references.d.ts +2 -2
- package/lib/languages/record-references.js +3 -2
- package/lib/languages/record-references.js.map +1 -0
- package/lib/languages/target-language.d.ts +0 -2
- package/lib/languages/target-language.js +2 -1
- package/lib/languages/target-language.js.map +1 -0
- package/lib/languages/visualize.d.ts +1 -1
- package/lib/languages/visualize.js +1 -1
- package/lib/languages/visualize.js.map +1 -0
- package/lib/logging.js +1 -1
- package/lib/logging.js.map +1 -0
- package/lib/main.d.ts +2 -0
- package/{bin/jsii-rosetta.js → lib/main.js} +21 -21
- package/lib/main.js.map +1 -0
- package/lib/markdown/escapes.js.map +1 -0
- package/lib/markdown/extract-snippets.d.ts +2 -2
- package/lib/markdown/extract-snippets.js +1 -1
- package/lib/markdown/extract-snippets.js.map +1 -0
- package/lib/markdown/index.js.map +1 -0
- package/lib/markdown/javadoc-renderer.js.map +1 -0
- package/lib/markdown/markdown-renderer.js.map +1 -0
- package/lib/markdown/markdown.js.map +1 -0
- package/lib/markdown/replace-code-renderer.d.ts +1 -1
- package/lib/markdown/replace-code-renderer.js.map +1 -0
- package/lib/markdown/replace-typescript-transform.d.ts +2 -2
- package/lib/markdown/replace-typescript-transform.js +1 -1
- package/lib/markdown/replace-typescript-transform.js.map +1 -0
- package/lib/markdown/structure-renderer.js.map +1 -0
- package/lib/markdown/types.js.map +1 -0
- package/lib/markdown/xml-comment-renderer.js.map +1 -0
- package/lib/o-tree.js +3 -3
- package/lib/o-tree.js.map +1 -0
- package/lib/renderer.js.map +1 -0
- package/lib/rosetta-reader.js.map +1 -0
- package/lib/rosetta-translator.d.ts +1 -1
- package/lib/rosetta-translator.js +2 -2
- package/lib/rosetta-translator.js.map +1 -0
- package/lib/snippet-dependencies.js +12 -12
- package/lib/snippet-dependencies.js.map +1 -0
- package/lib/snippet-selectors.d.ts +1 -1
- package/lib/snippet-selectors.js +2 -2
- package/lib/snippet-selectors.js.map +1 -0
- package/lib/snippet.d.ts +3 -3
- package/lib/snippet.js +5 -5
- package/lib/snippet.js.map +1 -0
- package/lib/strict.js.map +1 -0
- package/lib/submodule-reference.d.ts +1 -1
- package/lib/submodule-reference.js +11 -11
- package/lib/submodule-reference.js.map +1 -0
- package/lib/tablets/key.js +3 -3
- package/lib/tablets/key.js.map +1 -0
- package/lib/tablets/schema.js.map +1 -0
- package/lib/tablets/tablets.d.ts +1 -1
- package/lib/tablets/tablets.js +13 -13
- package/lib/tablets/tablets.js.map +1 -0
- package/lib/translate.d.ts +1 -1
- package/lib/translate.js +9 -7
- package/lib/translate.js.map +1 -0
- package/lib/translate_all.js +2 -2
- package/lib/translate_all.js.map +1 -0
- package/lib/translate_all_worker.js.map +1 -0
- package/lib/typescript/ast-utils.d.ts +2 -2
- package/lib/typescript/ast-utils.js +2 -4
- package/lib/typescript/ast-utils.js.map +1 -0
- package/lib/typescript/imports.d.ts +2 -2
- package/lib/typescript/imports.js +3 -3
- package/lib/typescript/imports.js.map +1 -0
- package/lib/typescript/syntax-kind-counter.d.ts +1 -1
- package/lib/typescript/syntax-kind-counter.js +1 -2
- package/lib/typescript/syntax-kind-counter.js.map +1 -0
- package/lib/typescript/ts-compiler.js.map +1 -0
- package/lib/typescript/types.d.ts +2 -2
- package/lib/typescript/types.js +1 -1
- package/lib/typescript/types.js.map +1 -0
- package/lib/typescript/visible-spans.js +6 -6
- package/lib/typescript/visible-spans.js.map +1 -0
- package/lib/util.d.ts +1 -1
- package/lib/util.js +2 -2
- package/lib/util.js.map +1 -0
- package/package.json +68 -37
- package/temp.tabl.json +48 -0
- package/bin/jsii-rosetta.d.ts +0 -2
- package/jest.config.mjs +0 -8
- package/jestsetup.js +0 -4
- package/test/commands/extract.test.d.ts +0 -2
- package/test/commands/extract.test.js +0 -698
- package/test/commands/infuse.test.d.ts +0 -2
- package/test/commands/infuse.test.js +0 -165
- package/test/commands/transliterate.test.d.ts +0 -2
- package/test/commands/transliterate.test.js +0 -1636
- package/test/commands/trim-cache.test.d.ts +0 -2
- package/test/commands/trim-cache.test.js +0 -85
- package/test/fixtures.test.d.ts +0 -2
- package/test/fixtures.test.js +0 -49
- package/test/jsii/assemblies.test.d.ts +0 -2
- package/test/jsii/assemblies.test.js +0 -230
- package/test/jsii/fake-assembly.d.ts +0 -3
- package/test/jsii/fake-assembly.js +0 -21
- package/test/jsii/fixtures/rosetta/explicit.ts-fixture +0 -7
- package/test/jsii/visible-spans.test.d.ts +0 -2
- package/test/jsii/visible-spans.test.js +0 -40
- package/test/jsii-imports.test.d.ts +0 -2
- package/test/jsii-imports.test.js +0 -438
- package/test/markdown/javadoc.test.d.ts +0 -2
- package/test/markdown/javadoc.test.js +0 -110
- package/test/markdown/roundtrip.test.d.ts +0 -2
- package/test/markdown/roundtrip.test.js +0 -126
- package/test/markdown/xmldoccomments.test.d.ts +0 -2
- package/test/markdown/xmldoccomments.test.js +0 -89
- package/test/otree.test.d.ts +0 -2
- package/test/otree.test.js +0 -36
- package/test/record-references.test.d.ts +0 -2
- package/test/record-references.test.js +0 -88
- package/test/rosetta/default.ts-fixture +0 -1
- package/test/rosetta-translator.test.d.ts +0 -2
- package/test/rosetta-translator.test.js +0 -33
- package/test/rosetta.test.d.ts +0 -2
- package/test/rosetta.test.js +0 -221
- package/test/snippet-selectors.test.d.ts +0 -2
- package/test/snippet-selectors.test.js +0 -57
- package/test/snippet.test.d.ts +0 -2
- package/test/snippet.test.js +0 -18
- package/test/syntax-counter.test.d.ts +0 -2
- package/test/syntax-counter.test.js +0 -60
- package/test/testutil.d.ts +0 -64
- package/test/testutil.js +0 -104
- package/test/translate.test.d.ts +0 -2
- package/test/translate.test.js +0 -175
- package/test/translations/calls/declaring_default_arguments.cs +0 -4
- package/test/translations/calls/declaring_default_arguments.go +0 -6
- package/test/translations/calls/declaring_default_arguments.java +0 -11
- package/test/translations/calls/declaring_default_arguments.py +0 -2
- package/test/translations/calls/default_struct_fields.cs +0 -9
- package/test/translations/calls/default_struct_fields.go +0 -7
- package/test/translations/calls/default_struct_fields.java +0 -21
- package/test/translations/calls/default_struct_fields.py +0 -2
- package/test/translations/calls/function_call.cs +0 -1
- package/test/translations/calls/function_call.go +0 -1
- package/test/translations/calls/function_call.java +0 -1
- package/test/translations/calls/function_call.py +0 -1
- package/test/translations/calls/list_of_anonymous_structs.cs +0 -9
- package/test/translations/calls/list_of_anonymous_structs.go +0 -12
- package/test/translations/calls/list_of_anonymous_structs.java +0 -6
- package/test/translations/calls/list_of_anonymous_structs.py +0 -9
- package/test/translations/calls/literal_map_argument.cs +0 -5
- package/test/translations/calls/literal_map_argument.go +0 -7
- package/test/translations/calls/literal_map_argument.java +0 -4
- package/test/translations/calls/literal_map_argument.py +0 -4
- package/test/translations/calls/method_call.cs +0 -1
- package/test/translations/calls/method_call.go +0 -1
- package/test/translations/calls/method_call.java +0 -1
- package/test/translations/calls/method_call.py +0 -1
- package/test/translations/calls/self_method_call.cs +0 -1
- package/test/translations/calls/self_method_call.go +0 -1
- package/test/translations/calls/self_method_call.java +0 -1
- package/test/translations/calls/self_method_call.py +0 -1
- package/test/translations/calls/shorthand_property.cs +0 -2
- package/test/translations/calls/shorthand_property.go +0 -4
- package/test/translations/calls/shorthand_property.java +0 -2
- package/test/translations/calls/shorthand_property.py +0 -2
- package/test/translations/calls/static_function_call.cs +0 -1
- package/test/translations/calls/static_function_call.go +0 -1
- package/test/translations/calls/static_function_call.java +0 -1
- package/test/translations/calls/static_function_call.py +0 -1
- package/test/translations/calls/this_argument.cs +0 -1
- package/test/translations/calls/this_argument.go +0 -1
- package/test/translations/calls/this_argument.java +0 -1
- package/test/translations/calls/this_argument.py +0 -1
- package/test/translations/calls/translate_object_literals_in_function_call.cs +0 -1
- package/test/translations/calls/translate_object_literals_in_function_call.go +0 -4
- package/test/translations/calls/translate_object_literals_in_function_call.java +0 -1
- package/test/translations/calls/translate_object_literals_in_function_call.py +0 -1
- package/test/translations/calls/translate_object_literals_only_one_level_deep.cs +0 -1
- package/test/translations/calls/translate_object_literals_only_one_level_deep.go +0 -7
- package/test/translations/calls/translate_object_literals_only_one_level_deep.java +0 -1
- package/test/translations/calls/translate_object_literals_only_one_level_deep.py +0 -1
- package/test/translations/calls/translate_object_literals_second_level_with_newlines.cs +0 -4
- package/test/translations/calls/translate_object_literals_second_level_with_newlines.go +0 -7
- package/test/translations/calls/translate_object_literals_second_level_with_newlines.java +0 -3
- package/test/translations/calls/translate_object_literals_second_level_with_newlines.py +0 -4
- package/test/translations/calls/translate_object_literals_with_multiple_newlines.cs +0 -5
- package/test/translations/calls/translate_object_literals_with_multiple_newlines.go +0 -5
- package/test/translations/calls/translate_object_literals_with_multiple_newlines.java +0 -4
- package/test/translations/calls/translate_object_literals_with_multiple_newlines.py +0 -5
- package/test/translations/calls/translate_object_literals_with_newlines.cs +0 -4
- package/test/translations/calls/translate_object_literals_with_newlines.go +0 -4
- package/test/translations/calls/translate_object_literals_with_newlines.java +0 -3
- package/test/translations/calls/translate_object_literals_with_newlines.py +0 -4
- package/test/translations/calls/will_type_deep_structs_directly_if_type_info_is_available.cs +0 -24
- package/test/translations/calls/will_type_deep_structs_directly_if_type_info_is_available.go +0 -24
- package/test/translations/calls/will_type_deep_structs_directly_if_type_info_is_available.java +0 -48
- package/test/translations/calls/will_type_deep_structs_directly_if_type_info_is_available.py +0 -7
- package/test/translations/classes/class_declaration_with_private_fields_and_constructor.cs +0 -9
- package/test/translations/classes/class_declaration_with_private_fields_and_constructor.go +0 -9
- package/test/translations/classes/class_declaration_with_private_fields_and_constructor.java +0 -7
- package/test/translations/classes/class_declaration_with_private_fields_and_constructor.py +0 -4
- package/test/translations/classes/class_declaration_with_public_fields_and_constructor.cs +0 -9
- package/test/translations/classes/class_declaration_with_public_fields_and_constructor.go +0 -9
- package/test/translations/classes/class_declaration_with_public_fields_and_constructor.java +0 -7
- package/test/translations/classes/class_declaration_with_public_fields_and_constructor.py +0 -4
- package/test/translations/classes/class_implementing_jsii_interface.cs +0 -7
- package/test/translations/classes/class_implementing_jsii_interface.go +0 -6
- package/test/translations/classes/class_implementing_jsii_interface.java +0 -5
- package/test/translations/classes/class_implementing_jsii_interface.py +0 -4
- package/test/translations/classes/class_with_different_name.cs +0 -6
- package/test/translations/classes/class_with_different_name.go +0 -7
- package/test/translations/classes/class_with_different_name.java +0 -4
- package/test/translations/classes/class_with_different_name.py +0 -3
- package/test/translations/classes/class_with_extends_and_implements.cs +0 -3
- package/test/translations/classes/class_with_extends_and_implements.go +0 -3
- package/test/translations/classes/class_with_extends_and_implements.java +0 -2
- package/test/translations/classes/class_with_inheritance.cs +0 -3
- package/test/translations/classes/class_with_inheritance.go +0 -3
- package/test/translations/classes/class_with_inheritance.java +0 -2
- package/test/translations/classes/class_with_inheritance.py +0 -2
- package/test/translations/classes/class_with_inheritance_and_super_class.cs +0 -6
- package/test/translations/classes/class_with_inheritance_and_super_class.go +0 -9
- package/test/translations/classes/class_with_inheritance_and_super_class.java +0 -5
- package/test/translations/classes/class_with_inheritance_and_super_class.py +0 -3
- package/test/translations/classes/class_with_method.cs +0 -7
- package/test/translations/classes/class_with_method.go +0 -7
- package/test/translations/classes/class_with_method.java +0 -5
- package/test/translations/classes/class_with_method.py +0 -3
- package/test/translations/classes/class_with_props_argument.cs +0 -14
- package/test/translations/classes/class_with_props_argument.go +0 -16
- package/test/translations/classes/class_with_props_argument.java +0 -26
- package/test/translations/classes/class_with_props_argument.py +0 -5
- package/test/translations/classes/constructor_with_optional_params.go +0 -10
- package/test/translations/classes/constructor_with_optional_params.java +0 -12
- package/test/translations/classes/empty_class.cs +0 -3
- package/test/translations/classes/empty_class.go +0 -2
- package/test/translations/classes/empty_class.java +0 -2
- package/test/translations/classes/empty_class.py +0 -2
- package/test/translations/classes/invisible_interfaces_do_not_affect_whitespace.cs +0 -11
- package/test/translations/classes/invisible_interfaces_do_not_affect_whitespace.go +0 -8
- package/test/translations/classes/invisible_interfaces_do_not_affect_whitespace.java +0 -8
- package/test/translations/classes/invisible_interfaces_do_not_affect_whitespace.py +0 -5
- package/test/translations/classes/whitespace_between_multiple_empty_members.cs +0 -15
- package/test/translations/classes/whitespace_between_multiple_empty_members.go +0 -12
- package/test/translations/classes/whitespace_between_multiple_empty_members.java +0 -11
- package/test/translations/classes/whitespace_between_multiple_empty_members.py +0 -9
- package/test/translations/classes/whitespace_between_multiple_members.cs +0 -17
- package/test/translations/classes/whitespace_between_multiple_members.go +0 -16
- package/test/translations/classes/whitespace_between_multiple_members.java +0 -13
- package/test/translations/classes/whitespace_between_multiple_members.py +0 -9
- package/test/translations/comments/empty_lines_in_comments.cs +0 -4
- package/test/translations/comments/empty_lines_in_comments.go +0 -4
- package/test/translations/comments/empty_lines_in_comments.java +0 -4
- package/test/translations/comments/empty_lines_in_comments.py +0 -4
- package/test/translations/comments/interleave_multiline_comments_with_function_call.cs +0 -7
- package/test/translations/comments/interleave_multiline_comments_with_function_call.go +0 -7
- package/test/translations/comments/interleave_multiline_comments_with_function_call.java +0 -6
- package/test/translations/comments/interleave_multiline_comments_with_function_call.py +0 -7
- package/test/translations/comments/interleave_single_line_comments_with_function_call.cs +0 -7
- package/test/translations/comments/interleave_single_line_comments_with_function_call.go +0 -7
- package/test/translations/comments/interleave_single_line_comments_with_function_call.java +0 -6
- package/test/translations/comments/interleave_single_line_comments_with_function_call.py +0 -7
- package/test/translations/comments/no_duplication_of_comments.cs +0 -2
- package/test/translations/comments/no_duplication_of_comments.go +0 -2
- package/test/translations/comments/no_duplication_of_comments.java +0 -2
- package/test/translations/comments/no_duplication_of_comments.py +0 -2
- package/test/translations/expressions/array_index.cs +0 -3
- package/test/translations/expressions/array_index.go +0 -3
- package/test/translations/expressions/array_index.java +0 -3
- package/test/translations/expressions/array_index.py +0 -3
- package/test/translations/expressions/as_expression.cs +0 -1
- package/test/translations/expressions/as_expression.go +0 -1
- package/test/translations/expressions/as_expression.java +0 -1
- package/test/translations/expressions/as_expression.py +0 -1
- package/test/translations/expressions/await.cs +0 -1
- package/test/translations/expressions/await.go +0 -1
- package/test/translations/expressions/await.java +0 -1
- package/test/translations/expressions/await.py +0 -1
- package/test/translations/expressions/backtick_string_w_o_substitutions.cs +0 -1
- package/test/translations/expressions/backtick_string_w_o_substitutions.go +0 -1
- package/test/translations/expressions/backtick_string_w_o_substitutions.java +0 -1
- package/test/translations/expressions/backtick_string_w_o_substitutions.py +0 -1
- package/test/translations/expressions/computed_key.cs +0 -4
- package/test/translations/expressions/computed_key.go +0 -8
- package/test/translations/expressions/computed_key.java +0 -4
- package/test/translations/expressions/computed_key.py +0 -4
- package/test/translations/expressions/double_quoted_dict_keys.cs +0 -1
- package/test/translations/expressions/double_quoted_dict_keys.go +0 -3
- package/test/translations/expressions/double_quoted_dict_keys.java +0 -1
- package/test/translations/expressions/double_quoted_dict_keys.py +0 -1
- package/test/translations/expressions/ellipsis_at_a_random_place.cs +0 -1
- package/test/translations/expressions/ellipsis_at_a_random_place.go +0 -1
- package/test/translations/expressions/ellipsis_at_a_random_place.java +0 -1
- package/test/translations/expressions/ellipsis_at_a_random_place.py +0 -1
- package/test/translations/expressions/enum_access.cs +0 -1
- package/test/translations/expressions/enum_access.go +0 -1
- package/test/translations/expressions/enum_access.java +0 -1
- package/test/translations/expressions/enum_access.py +0 -1
- package/test/translations/expressions/enum_like_access.cs +0 -1
- package/test/translations/expressions/enum_like_access.go +0 -1
- package/test/translations/expressions/enum_like_access.java +0 -1
- package/test/translations/expressions/enum_like_access.py +0 -1
- package/test/translations/expressions/map-literal.cs +0 -3
- package/test/translations/expressions/map-literal.go +0 -3
- package/test/translations/expressions/map-literal.java +0 -2
- package/test/translations/expressions/map-literal.py +0 -3
- package/test/translations/expressions/non_null_expression.cs +0 -1
- package/test/translations/expressions/non_null_expression.go +0 -1
- package/test/translations/expressions/non_null_expression.java +0 -1
- package/test/translations/expressions/non_null_expression.py +0 -1
- package/test/translations/expressions/string_interpolation.cs +0 -10
- package/test/translations/expressions/string_interpolation.go +0 -6
- package/test/translations/expressions/string_interpolation.java +0 -6
- package/test/translations/expressions/string_interpolation.py +0 -10
- package/test/translations/expressions/string_literal.cs +0 -9
- package/test/translations/expressions/string_literal.go +0 -9
- package/test/translations/expressions/string_literal.java +0 -1
- package/test/translations/expressions/string_literal.py +0 -9
- package/test/translations/expressions/struct_assignment.cs +0 -6
- package/test/translations/expressions/struct_assignment.go +0 -7
- package/test/translations/expressions/struct_assignment.java +0 -12
- package/test/translations/expressions/struct_assignment.py +0 -1
- package/test/translations/expressions/unary_and_binary_operators.cs +0 -3
- package/test/translations/expressions/unary_and_binary_operators.go +0 -3
- package/test/translations/expressions/unary_and_binary_operators.java +0 -3
- package/test/translations/expressions/unary_and_binary_operators.py +0 -3
- package/test/translations/hiding/hide_block_level_statements_using_void_directive.cs +0 -6
- package/test/translations/hiding/hide_block_level_statements_using_void_directive.go +0 -5
- package/test/translations/hiding/hide_block_level_statements_using_void_directive.java +0 -5
- package/test/translations/hiding/hide_block_level_statements_using_void_directive.py +0 -4
- package/test/translations/hiding/hide_expression_with_explicit_ellipsis.cs +0 -1
- package/test/translations/hiding/hide_expression_with_explicit_ellipsis.go +0 -1
- package/test/translations/hiding/hide_expression_with_explicit_ellipsis.java +0 -1
- package/test/translations/hiding/hide_expression_with_explicit_ellipsis.py +0 -1
- package/test/translations/hiding/hide_halfway_into_class_using_comments.cs +0 -3
- package/test/translations/hiding/hide_halfway_into_class_using_comments.go +0 -3
- package/test/translations/hiding/hide_halfway_into_class_using_comments.java +0 -3
- package/test/translations/hiding/hide_halfway_into_class_using_comments.py +0 -3
- package/test/translations/hiding/hide_parameter_sequence.cs +0 -1
- package/test/translations/hiding/hide_parameter_sequence.go +0 -1
- package/test/translations/hiding/hide_parameter_sequence.java +0 -1
- package/test/translations/hiding/hide_parameter_sequence.py +0 -1
- package/test/translations/hiding/hide_statements_with_explicit_ellipsis.cs +0 -3
- package/test/translations/hiding/hide_statements_with_explicit_ellipsis.go +0 -3
- package/test/translations/hiding/hide_statements_with_explicit_ellipsis.java +0 -3
- package/test/translations/hiding/hide_statements_with_explicit_ellipsis.py +0 -3
- package/test/translations/hiding/hide_top_level_statements_using_void_directive.cs +0 -1
- package/test/translations/hiding/hide_top_level_statements_using_void_directive.go +0 -1
- package/test/translations/hiding/hide_top_level_statements_using_void_directive.java +0 -1
- package/test/translations/hiding/hide_top_level_statements_using_void_directive.py +0 -1
- package/test/translations/identifiers/keyword.cs +0 -4
- package/test/translations/identifiers/keyword.go +0 -4
- package/test/translations/identifiers/keyword.java +0 -4
- package/test/translations/identifiers/keyword.py +0 -4
- package/test/translations/imports/import_require.cs +0 -2
- package/test/translations/imports/import_require.go +0 -2
- package/test/translations/imports/import_require.java +0 -2
- package/test/translations/imports/import_require.py +0 -2
- package/test/translations/imports/import_star_as.cs +0 -2
- package/test/translations/imports/import_star_as.go +0 -2
- package/test/translations/imports/import_star_as.java +0 -2
- package/test/translations/imports/import_star_as.py +0 -2
- package/test/translations/imports/multiple-imports.cs +0 -2
- package/test/translations/imports/multiple-imports.go +0 -2
- package/test/translations/imports/multiple-imports.java +0 -3
- package/test/translations/imports/multiple-imports.py +0 -2
- package/test/translations/imports/selective_import.cs +0 -4
- package/test/translations/imports/selective_import.go +0 -3
- package/test/translations/imports/selective_import.java +0 -6
- package/test/translations/imports/selective_import.py +0 -3
- package/test/translations/imports/submodule-import.cs +0 -15
- package/test/translations/imports/submodule-import.go +0 -23
- package/test/translations/imports/submodule-import.java +0 -17
- package/test/translations/imports/submodule-import.py +0 -15
- package/test/translations/interfaces/interface_with_method.cs +0 -4
- package/test/translations/interfaces/interface_with_method.go +0 -3
- package/test/translations/interfaces/interface_with_method.java +0 -3
- package/test/translations/interfaces/interface_with_props.cs +0 -4
- package/test/translations/interfaces/interface_with_props.go +0 -3
- package/test/translations/interfaces/interface_with_props.java +0 -3
- package/test/translations/misc/booleans_render_to_right_primitives.cs +0 -1
- package/test/translations/misc/booleans_render_to_right_primitives.go +0 -1
- package/test/translations/misc/booleans_render_to_right_primitives.java +0 -1
- package/test/translations/misc/booleans_render_to_right_primitives.py +0 -1
- package/test/translations/statements/block_without_braces.cs +0 -1
- package/test/translations/statements/block_without_braces.go +0 -3
- package/test/translations/statements/block_without_braces.java +0 -1
- package/test/translations/statements/block_without_braces.py +0 -1
- package/test/translations/statements/declare_var.cs +0 -1
- package/test/translations/statements/declare_var.go +0 -1
- package/test/translations/statements/declare_var.java +0 -1
- package/test/translations/statements/declare_var.py +0 -1
- package/test/translations/statements/empty_control_block.cs +0 -3
- package/test/translations/statements/empty_control_block.go +0 -1
- package/test/translations/statements/empty_control_block.java +0 -2
- package/test/translations/statements/empty_control_block.py +0 -2
- package/test/translations/statements/for_of_loop.cs +0 -4
- package/test/translations/statements/for_of_loop.go +0 -3
- package/test/translations/statements/for_of_loop.java +0 -3
- package/test/translations/statements/for_of_loop.py +0 -2
- package/test/translations/statements/if.cs +0 -4
- package/test/translations/statements/if.go +0 -3
- package/test/translations/statements/if.java +0 -3
- package/test/translations/statements/if.py +0 -2
- package/test/translations/statements/if_then_else.cs +0 -8
- package/test/translations/statements/if_then_else.go +0 -5
- package/test/translations/statements/if_then_else.java +0 -5
- package/test/translations/statements/if_then_else.py +0 -4
- package/test/translations/statements/initialize_object_literal.cs +0 -5
- package/test/translations/statements/initialize_object_literal.go +0 -8
- package/test/translations/statements/initialize_object_literal.java +0 -4
- package/test/translations/statements/initialize_object_literal.py +0 -5
- package/test/translations/statements/multiline_if_then_else.cs +0 -9
- package/test/translations/statements/multiline_if_then_else.go +0 -6
- package/test/translations/statements/multiline_if_then_else.java +0 -6
- package/test/translations/statements/multiline_if_then_else.py +0 -5
- package/test/translations/statements/statements_and_newlines.cs +0 -26
- package/test/translations/statements/statements_and_newlines.go +0 -21
- package/test/translations/statements/statements_and_newlines.java +0 -21
- package/test/translations/statements/statements_and_newlines.py +0 -16
- package/test/translations/statements/vararg_any_call.cs +0 -7
- package/test/translations/statements/vararg_any_call.go +0 -13
- package/test/translations/statements/vararg_any_call.java +0 -6
- package/test/translations/statements/vararg_any_call.py +0 -6
- package/test/translations/statements/whitespace_between_statements.cs +0 -3
- package/test/translations/statements/whitespace_between_statements.go +0 -3
- package/test/translations/statements/whitespace_between_statements.java +0 -3
- package/test/translations/statements/whitespace_between_statements.py +0 -3
- package/test/translations/statements/whitespace_between_statements_in_a_block.cs +0 -6
- package/test/translations/statements/whitespace_between_statements_in_a_block.go +0 -5
- package/test/translations/statements/whitespace_between_statements_in_a_block.java +0 -5
- package/test/translations/statements/whitespace_between_statements_in_a_block.py +0 -4
- package/test/translations/structs/any_type_never_a_struct.cs +0 -3
- package/test/translations/structs/any_type_never_a_struct.go +0 -3
- package/test/translations/structs/any_type_never_a_struct.java +0 -2
- package/test/translations/structs/any_type_never_a_struct.py +0 -3
- package/test/translations/structs/infer_struct_from_union.cs +0 -6
- package/test/translations/structs/infer_struct_from_union.go +0 -8
- package/test/translations/structs/infer_struct_from_union.java +0 -6
- package/test/translations/structs/infer_struct_from_union.py +0 -6
- package/test/translations/structs/optional_known_struct.cs +0 -3
- package/test/translations/structs/optional_known_struct.go +0 -3
- package/test/translations/structs/optional_known_struct.java +0 -3
- package/test/translations/structs/optional_known_struct.py +0 -3
- package/test/translations/structs/struct_starting_with_i.cs +0 -3
- package/test/translations/structs/struct_starting_with_i.go +0 -3
- package/test/translations/structs/struct_starting_with_i.java +0 -3
- package/test/translations/structs/struct_starting_with_i.py +0 -3
- package/test/translations/structs/var_new_class_known_struct.cs +0 -3
- package/test/translations/structs/var_new_class_known_struct.go +0 -3
- package/test/translations/structs/var_new_class_known_struct.java +0 -3
- package/test/translations/structs/var_new_class_known_struct.py +0 -3
- package/test/translations/structs/var_new_class_unknown_struct.cs +0 -3
- package/test/translations/structs/var_new_class_unknown_struct.go +0 -3
- package/test/translations/structs/var_new_class_unknown_struct.java +0 -3
- package/test/translations/structs/var_new_class_unknown_struct.py +0 -3
- package/test/translations.test.d.ts +0 -9
- package/test/translations.test.js +0 -112
- package/test/util.test.d.ts +0 -2
- package/test/util.test.js +0 -25
- package/vendor/semver-intersect.d.ts +0 -13
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"o-tree.js","sourceRoot":"","sources":["../src/o-tree.ts"],"names":[],"mappings":";;;AAuDA;;;;;GAKG;AACH,MAAa,KAAK;IACT,MAAM,CAAC,QAAQ,CAAC,EAAqC;QAC1D,OAAO,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAClD,CAAC;IAQD,YACE,MAAyC,EACzC,QAA4C,EAC3B,UAAwB,EAAE;QAA1B,YAAO,GAAP,OAAO,CAAmB;QAE3C,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACrC,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;QAC/C,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC;IAC9C,CAAC;IAED;;OAEG;IACI,OAAO,CAAC,KAAa,EAAE,GAAW;QACvC,IAAI,CAAC,IAAI,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;IAC7B,CAAC;IAEM,KAAK,CAAC,IAAe;QAC1B,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE;YAC1C,OAAO;SACR;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEnD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE;YAC3B,IAAI,CAAC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,CAAC,CAAC;IACpC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACjB,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC;AACzB,CAAC;AAJD,gCAIC;AAED,SAAS,eAAe,CAAC,CAAS;IAChC,OAAO,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { Spans } from './typescript/visible-spans';\n\nexport interface OTreeOptions {\n /**\n * Adjust indentation with the given number\n *\n * Indentation affects children.\n *\n * @default 0\n */\n indent?: number;\n\n /**\n * Separate children with the given string\n *\n * @default ''\n */\n separator?: string;\n\n /**\n * Whether trailing separators should be output. This imples children will be\n * writen each on a new line.\n *\n * @default false\n */\n trailingSeparator?: boolean;\n\n /**\n * Suffix the token after outdenting\n *\n * @default ''\n */\n suffix?: string;\n\n /**\n * Whether this part of the generated syntax is okay to insert newlines and comments\n *\n * @default false\n */\n canBreakLine?: boolean;\n\n /**\n * If set, a unique key which will cause only one node with the given key to be rendered.\n *\n * The outermost key is the one that will be rendered.\n *\n * Used to make it easier to keep the state necessary to render comments\n * only once in the output tree, rather than keep the state in the\n * language rendered.\n *\n * @default No conditional rendering\n */\n renderOnce?: string;\n}\n\n/**\n * \"Output\" Tree\n *\n * Tree-like structure that holds sequences of trees and strings, which\n * can be rendered to an output sink.\n */\nexport class OTree implements OTree {\n public static simplify(xs: Array<OTree | string | undefined>): Array<OTree | string> {\n return xs.filter(notUndefined).filter(notEmpty);\n }\n\n public readonly attachComment: boolean;\n\n private readonly prefix: Array<OTree | string>;\n private readonly children: Array<OTree | string>;\n private span?: Span;\n\n public constructor(\n prefix: Array<OTree | string | undefined>,\n children?: Array<OTree | string | undefined>,\n private readonly options: OTreeOptions = {},\n ) {\n this.prefix = OTree.simplify(prefix);\n this.children = OTree.simplify(children ?? []);\n this.attachComment = !!options.canBreakLine;\n }\n\n /**\n * Set the span in the source file this tree node relates to\n */\n public setSpan(start: number, end: number) {\n this.span = { start, end };\n }\n\n public write(sink: OTreeSink) {\n if (!sink.tagOnce(this.options.renderOnce)) {\n return;\n }\n\n const meVisible = sink.renderingForSpan(this.span);\n\n for (const x of this.prefix) {\n sink.write(x);\n }\n\n const popIndent = sink.requestIndentChange(meVisible ? this.options.indent ?? 0 : 0);\n let mark = sink.mark();\n\n for (const child of this.children ?? []) {\n if (this.options.separator) {\n if (this.options.trailingSeparator) {\n sink.ensureNewLine();\n } else if (mark.wroteNonWhitespaceSinceMark) {\n sink.write(this.options.separator);\n }\n }\n mark = sink.mark();\n\n sink.write(child);\n\n if (this.options.separator && this.options.trailingSeparator) {\n sink.write(this.options.separator.trimEnd());\n }\n }\n\n popIndent();\n\n if (this.options.suffix) {\n if (this.options.separator && this.options.trailingSeparator) {\n sink.ensureNewLine();\n }\n sink.renderingForSpan(this.span);\n sink.write(this.options.suffix);\n }\n }\n\n public get isEmpty() {\n return this.prefix.length + this.children.length === 0;\n }\n\n public toString() {\n return `<INCORRECTLY STRINGIFIED ${this.prefix.toString()}>`;\n }\n}\n\nexport const NO_SYNTAX = new OTree([]);\n\nexport class UnknownSyntax extends OTree {}\n\nexport interface SinkMark {\n readonly wroteNonWhitespaceSinceMark: boolean;\n}\n\nexport interface OTreeSinkOptions {\n /**\n * @default ' '\n */\n indentChar?: ' ' | '\\t';\n visibleSpans?: Spans;\n}\n\ninterface ConditionalNewLine {\n readonly conditionalNewLine: {\n readonly indent: number;\n };\n}\n\n/**\n * Output sink for OTree objects\n *\n * Maintains state about what has been rendered supports suppressing code\n * fragments based on their tagged source location.\n *\n * Basically: manages the state that was too hard to manage in the\n * tree :).\n */\nexport class OTreeSink {\n private readonly indentChar: ' ' | '\\t';\n private readonly indentLevels: number[] = [0];\n private readonly fragments = new Array<string | ConditionalNewLine>();\n private readonly singletonsRendered = new Set<string>();\n private pendingIndentChange = 0;\n private rendering = true;\n\n public constructor(private readonly options: OTreeSinkOptions = {}) {\n this.indentChar = options.indentChar ?? ' ';\n }\n\n public tagOnce(key: string | undefined): boolean {\n if (key === undefined) {\n return true;\n }\n if (this.singletonsRendered.has(key)) {\n return false;\n }\n this.singletonsRendered.add(key);\n return true;\n }\n\n /**\n * Get a mark for the current sink output location\n *\n * Marks can be used to query about things that have been written to output.\n */\n public mark(): SinkMark {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const markIndex = this.fragments.length;\n\n return {\n get wroteNonWhitespaceSinceMark(): boolean {\n return self.fragments.slice(markIndex).some((s) => typeof s !== 'object' && /[^\\s]/.exec(s) != null);\n },\n };\n }\n\n public write(text: string | OTree) {\n if (text instanceof OTree) {\n text.write(this);\n } else {\n if (!this.rendering) {\n return;\n }\n\n if (containsNewline(text)) {\n this.applyPendingIndentChange();\n }\n this.append(text.replace(/\\n/g, `\\n${this.indentChar.repeat(this.currentIndent)}`));\n }\n }\n\n /**\n * Ensures the following tokens will be output on a new line (emits a new line\n * and indent unless immediately preceded or followed by a newline, ignoring\n * surrounding white space).\n */\n public ensureNewLine(): void {\n this.applyPendingIndentChange();\n this.fragments.push({ conditionalNewLine: { indent: this.currentIndent } });\n }\n\n public renderingForSpan(span?: Span): boolean {\n if (span && this.options.visibleSpans) {\n this.rendering = this.options.visibleSpans.fullyContainsSpan(span);\n }\n return this.rendering;\n }\n\n public requestIndentChange(x: number): () => void {\n if (x === 0) {\n return () => undefined;\n }\n\n this.pendingIndentChange = x;\n const currentIndentState = this.indentLevels.length;\n\n // Return a pop function which will reset to the current indent state,\n // regardless of whether the indent was actually applied or not.\n return () => {\n this.indentLevels.splice(currentIndentState);\n this.pendingIndentChange = 0;\n };\n }\n\n public toString() {\n // Strip trailing whitespace from every line, and empty lines from the start and end\n return this.fragments\n .map((item, index, fragments) => {\n if (typeof item !== 'object') {\n return item;\n }\n const ignore = '';\n\n const leading = fragments.slice(0, index).reverse();\n for (const fragment of leading) {\n if (typeof fragment === 'object') {\n // We don't emit if there was already a conditional newline just before\n return ignore;\n }\n // If there's a trailing newline, then we don't emit this one\n if (/\\n\\s*$/m.exec(fragment)) {\n return ignore;\n }\n // If it contained non-whitespace characters, we need to check trailing data...\n if (/[^\\s]/.exec(fragment)) {\n break;\n }\n }\n\n const newlineAndIndent = `\\n${this.indentChar.repeat(item.conditionalNewLine.indent)}`;\n\n const trailing = fragments.slice(index + 1);\n for (const fragment of trailing) {\n if (typeof fragment === 'object') {\n // We're the first of a sequence, so we must emit (unless we returned earlier, of course)\n return newlineAndIndent;\n }\n // If there's a leading newline, then we don't emit this one\n if (/^\\s*\\n/m.exec(fragment)) {\n return ignore;\n }\n // If it contained non-whitespace characters, we emit this one\n if (/[^\\s]/.exec(fragment)) {\n return newlineAndIndent;\n }\n }\n\n return ignore;\n })\n .join('')\n .replace(/[ \\t]+$/gm, '')\n .replace(/^\\n+/, '')\n .replace(/\\n+$/, '');\n }\n\n private append(x: string) {\n this.fragments.push(x);\n }\n\n private applyPendingIndentChange() {\n if (this.pendingIndentChange !== 0) {\n this.indentLevels.push(this.currentIndent + this.pendingIndentChange);\n this.pendingIndentChange = 0;\n }\n }\n\n private get currentIndent() {\n return this.indentLevels[this.indentLevels.length - 1];\n }\n}\n\nfunction notUndefined<T>(x: T | undefined): x is T {\n return x !== undefined;\n}\n\nfunction notEmpty(x: OTree | string) {\n return x instanceof OTree ? !x.isEmpty : x !== '';\n}\n\nexport function renderTree(tree: OTree, options?: OTreeSinkOptions): string {\n const sink = new OTreeSink(options);\n tree.write(sink);\n return sink.toString();\n}\n\nfunction containsNewline(x: string) {\n return x.includes('\\n');\n}\n\nexport interface Span {\n readonly start: number;\n readonly end: number;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAGjC,qCAAiE;AAEjE,sDAOgC;AAChC,kDAAsG;AACtG,8CAAgF;AAEhF;;;;;;;GAOG;AACH,MAAa,WAAW;IAItB,YACmB,UAAyB,EAC1B,WAA2B,EAC1B,OAAsB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C,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC;KAC/C,CAAC;AACJ,CAAC","sourcesContent":["import * as ts from 'typescript';\n\nimport { TargetLanguage } from './languages';\nimport { NO_SYNTAX, OTree, UnknownSyntax, Span } from './o-tree';\nimport { SubmoduleReference, SubmoduleReferenceMap } from './submodule-reference';\nimport {\n commentRangeFromTextRange,\n extractMaskingVoidExpression,\n extractShowingVoidExpression,\n nodeChildren,\n repeatNewlines,\n scanText,\n} from './typescript/ast-utils';\nimport { analyzeImportDeclaration, analyzeImportEquals, ImportStatement } from './typescript/imports';\nimport { typeOfExpression, inferredTypeOfExpression } from './typescript/types';\n\n/**\n * Render a TypeScript AST to some other representation (encoded in OTrees)\n *\n * Dispatch the actual conversion to a specific handler which will get the\n * appropriate method called for particular AST nodes. The handler may use\n * context to modify its own operations when traversing the tree hierarchy,\n * the type of which should be expressed via the C parameter.\n */\nexport class AstRenderer<C> {\n public readonly diagnostics = new Array<ts.Diagnostic>();\n public readonly currentContext: C;\n\n public constructor(\n private readonly sourceFile: ts.SourceFile,\n public readonly typeChecker: ts.TypeChecker,\n private readonly handler: AstHandler<C>,\n private readonly options: AstRendererOptions = {},\n public readonly submoduleReferences: SubmoduleReferenceMap = new Map(),\n ) {\n this.currentContext = handler.defaultContext;\n }\n\n /**\n * Merge the new context with the current context and create a new Converter from it\n */\n public updateContext(contextUpdate: Partial<C>): AstRenderer<C> {\n const newContext = this.handler.mergeContext(this.currentContext, contextUpdate);\n\n // Use prototypal inheritance to create a version of 'this' in which only\n // 'currentContext' is updated.\n return Object.assign(Object.create(this), {\n currentContext: newContext,\n });\n }\n\n /**\n * Convert a single node to an OTree\n */\n public convert(node: ts.Node | undefined): OTree {\n if (node === undefined) {\n return NO_SYNTAX;\n }\n\n // Basic transform of node\n const transformed = this.dispatch(node);\n transformed.setSpan(node.getStart(this.sourceFile), node.getEnd());\n if (!transformed.attachComment) {\n return transformed;\n }\n\n const withTrivia = this.attachLeadingTrivia(node, transformed);\n withTrivia.setSpan(node.getStart(this.sourceFile), node.getEnd());\n return withTrivia;\n }\n\n /**\n * Convert a set of nodes, filtering out hidden nodes\n */\n public convertAll(nodes: readonly ts.Node[]): OTree[] {\n return filterVisible(nodes).map(this.convert.bind(this));\n }\n\n public convertWithModifier(\n nodes: readonly ts.Node[],\n makeContext: (context: this, node: ts.Node, index: number) => AstRenderer<C>,\n ): OTree[] {\n const vis = assignVisibility(nodes);\n const result = new Array<OTree>();\n for (const [idx, { node, visible, maskingVoid }] of vis.entries()) {\n const renderedNode = visible ? node : maskingVoid;\n if (renderedNode) {\n const context = makeContext(this, renderedNode, idx);\n result.push(context.convert(renderedNode));\n }\n }\n return result;\n }\n\n /**\n * Convert a set of nodes, but update the context for the last one.\n *\n * Takes visibility into account.\n */\n public convertLastDifferently(nodes: readonly ts.Node[], lastContext: C): OTree[] {\n const lastConverter = this.updateContext(lastContext);\n\n const convert = this.convert.bind(this);\n const lastConvert = lastConverter.convert.bind(lastConverter);\n\n const ret: OTree[] = [];\n\n const vis = assignVisibility(nodes);\n for (let i = 0; i < vis.length; i++) {\n const whichConvert = i === vis.length - 1 ? lastConvert : convert;\n\n const node = vis[i].visible ? vis[i].node : vis[i].maskingVoid;\n if (node) {\n ret.push(whichConvert(node));\n }\n }\n\n return ret;\n }\n\n public getPosition(node: ts.Node): Span {\n return {\n start: node.getStart(this.sourceFile),\n end: node.getEnd(),\n };\n }\n\n public textOf(node: ts.Node): string {\n return node.getText(this.sourceFile);\n }\n\n public textAt(pos: number, end: number): string {\n return this.sourceFile.text.substring(pos, end);\n }\n\n /**\n * Infer type of expression by the argument it is assigned to\n *\n * If the type of the expression can include undefined (if the value is\n * optional), `undefined` will be removed from the union.\n *\n * (Will return undefined for object literals not unified with a declared type)\n *\n * @deprecated Use `inferredTypeOfExpression` instead\n */\n public inferredTypeOfExpression(node: ts.Expression) {\n return inferredTypeOfExpression(this.typeChecker, node);\n }\n\n /**\n * Type of expression from the text of the expression\n *\n * (Will return a map type for object literals)\n *\n * @deprecated Use `typeOfExpression` directly\n */\n public typeOfExpression(node: ts.Expression): ts.Type {\n return typeOfExpression(this.typeChecker, node);\n }\n\n public typeOfType(node: ts.TypeNode): ts.Type {\n return this.typeChecker.getTypeFromTypeNode(node);\n }\n\n public typeToString(type: ts.Type) {\n return this.typeChecker.typeToString(type);\n }\n\n public report(node: ts.Node, messageText: string, category: ts.DiagnosticCategory = ts.DiagnosticCategory.Error) {\n this.diagnostics.push({\n category,\n code: 0,\n source: 'rosetta',\n messageText,\n file: this.sourceFile,\n start: node.getStart(this.sourceFile),\n length: node.getWidth(this.sourceFile),\n });\n }\n\n public reportUnsupported(node: ts.Node, language: TargetLanguage | undefined): void {\n const nodeKind = ts.SyntaxKind[node.kind];\n // tslint:disable-next-line:max-line-length\n if (language) {\n this.report(\n node,\n `This TypeScript feature (${nodeKind}) is not supported in examples because we cannot translate it to ${language}. Please rewrite this example.`,\n );\n } else {\n this.report(\n node,\n `This TypeScript feature (${nodeKind}) is not supported in examples. Please rewrite this example.`,\n );\n }\n }\n\n /**\n * Whether there is non-whitespace on the same line before the given position\n */\n public codeOnLineBefore(pos: number) {\n const text = this.sourceFile.text;\n while (pos > 0) {\n const c = text[--pos];\n if (c === '\\n') {\n return false;\n }\n if (c !== ' ' && c !== '\\r' && c !== '\\t') {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return a newline if the given node is preceded by at least one newline\n *\n * Used to mirror newline use between matchin brackets (such as { ... } and [ ... ]).\n */\n public mirrorNewlineBefore(viz?: ts.Node, suffix = '', otherwise = ''): string {\n if (viz === undefined) {\n return suffix;\n }\n\n // Return a newline if the given node is preceded by newlines\n const leadingRanges = scanText(this.sourceFile.text, viz.getFullStart(), viz.getStart(this.sourceFile));\n const newlines = [];\n\n for (const range of leadingRanges) {\n if (range.type === 'other') {\n newlines.push(repeatNewlines(this.sourceFile.text.substring(range.pos, range.end)));\n }\n }\n\n return (newlines.join('').length > 0 ? '\\n' : otherwise) + suffix;\n }\n\n /**\n * Dispatch node to handler\n */\n private dispatch(tree: ts.Node): OTree {\n const visitor = this.handler;\n\n // Using a switch on tree.kind + forced down-casting, because this is significantly faster than\n // doing a cascade of `if` statements with the `ts.is<NodeType>` functions, since `tree.kind` is\n // effectively integers, and this switch statement is hence optimizable to a jump table. This is\n // a VERY significant enhancement to the debugging experience, too.\n switch (tree.kind) {\n case ts.SyntaxKind.EmptyStatement:\n // Additional semicolon where it doesn't belong.\n return NO_SYNTAX;\n case ts.SyntaxKind.SourceFile:\n return visitor.sourceFile(tree as ts.SourceFile, this);\n case ts.SyntaxKind.ImportEqualsDeclaration:\n return visitor.importStatement(analyzeImportEquals(tree as ts.ImportEqualsDeclaration, this), this);\n case ts.SyntaxKind.ImportDeclaration:\n return new OTree(\n [],\n analyzeImportDeclaration(tree as ts.ImportDeclaration, this, this.submoduleReferences).map((import_) =>\n visitor.importStatement(import_, this),\n ),\n { canBreakLine: true, separator: '\\n' },\n );\n case ts.SyntaxKind.StringLiteral:\n case ts.SyntaxKind.NoSubstitutionTemplateLiteral:\n return visitor.stringLiteral(tree as ts.StringLiteral | ts.NoSubstitutionTemplateLiteral, this);\n case ts.SyntaxKind.NumericLiteral:\n return visitor.numericLiteral(tree as ts.NumericLiteral, this);\n case ts.SyntaxKind.FunctionDeclaration:\n return visitor.functionDeclaration(tree as ts.FunctionDeclaration, this);\n case ts.SyntaxKind.Identifier:\n return visitor.identifier(tree as ts.Identifier, this);\n case ts.SyntaxKind.Block:\n return visitor.block(tree as ts.Block, this);\n case ts.SyntaxKind.Parameter:\n return visitor.parameterDeclaration(tree as ts.ParameterDeclaration, this);\n case ts.SyntaxKind.ReturnStatement:\n return visitor.returnStatement(tree as ts.ReturnStatement, this);\n case ts.SyntaxKind.BinaryExpression:\n return visitor.binaryExpression(tree as ts.BinaryExpression, this);\n case ts.SyntaxKind.IfStatement:\n return visitor.ifStatement(tree as ts.IfStatement, this);\n case ts.SyntaxKind.PropertyAccessExpression:\n const submoduleReference = this.submoduleReferences?.get(tree as ts.PropertyAccessExpression);\n return visitor.propertyAccessExpression(tree as ts.PropertyAccessExpression, this, submoduleReference);\n case ts.SyntaxKind.AwaitExpression:\n return visitor.awaitExpression(tree as ts.AwaitExpression, this);\n case ts.SyntaxKind.CallExpression:\n return visitor.callExpression(tree as ts.CallExpression, this);\n case ts.SyntaxKind.ExpressionStatement:\n return visitor.expressionStatement(tree as ts.ExpressionStatement, this);\n case ts.SyntaxKind.ObjectLiteralExpression:\n return visitor.objectLiteralExpression(tree as ts.ObjectLiteralExpression, this);\n case ts.SyntaxKind.NewExpression:\n return visitor.newExpression(tree as ts.NewExpression, this);\n case ts.SyntaxKind.PropertyAssignment:\n return visitor.propertyAssignment(tree as ts.PropertyAssignment, this);\n case ts.SyntaxKind.VariableStatement:\n return visitor.variableStatement(tree as ts.VariableStatement, this);\n case ts.SyntaxKind.VariableDeclarationList:\n return visitor.variableDeclarationList(tree as ts.VariableDeclarationList, this);\n case ts.SyntaxKind.VariableDeclaration:\n return visitor.variableDeclaration(tree as ts.VariableDeclaration, this);\n case ts.SyntaxKind.ArrayLiteralExpression:\n return visitor.arrayLiteralExpression(tree as ts.ArrayLiteralExpression, this);\n case ts.SyntaxKind.ShorthandPropertyAssignment:\n return visitor.shorthandPropertyAssignment(tree as ts.ShorthandPropertyAssignment, this);\n case ts.SyntaxKind.ForOfStatement:\n return visitor.forOfStatement(tree as ts.ForOfStatement, this);\n case ts.SyntaxKind.ClassDeclaration:\n return visitor.classDeclaration(tree as ts.ClassDeclaration, this);\n case ts.SyntaxKind.Constructor:\n return visitor.constructorDeclaration(tree as ts.ConstructorDeclaration, this);\n case ts.SyntaxKind.PropertyDeclaration:\n return visitor.propertyDeclaration(tree as ts.PropertyDeclaration, this);\n case ts.SyntaxKind.ComputedPropertyName:\n return visitor.computedPropertyName((tree as ts.ComputedPropertyName).expression, this);\n case ts.SyntaxKind.MethodDeclaration:\n return visitor.methodDeclaration(tree as ts.MethodDeclaration, this);\n case ts.SyntaxKind.InterfaceDeclaration:\n return visitor.interfaceDeclaration(tree as ts.InterfaceDeclaration, this);\n case ts.SyntaxKind.PropertySignature:\n return visitor.propertySignature(tree as ts.PropertySignature, this);\n case ts.SyntaxKind.MethodSignature:\n return visitor.methodSignature(tree as ts.MethodSignature, this);\n case ts.SyntaxKind.AsExpression:\n return visitor.asExpression(tree as ts.AsExpression, this);\n case ts.SyntaxKind.PrefixUnaryExpression:\n return visitor.prefixUnaryExpression(tree as ts.PrefixUnaryExpression, this);\n case ts.SyntaxKind.SpreadAssignment:\n if (this.textOf(tree) === '...') {\n return visitor.ellipsis(tree as ts.SpreadAssignment, this);\n }\n return visitor.spreadAssignment(tree as ts.SpreadAssignment, this);\n case ts.SyntaxKind.SpreadElement:\n if (this.textOf(tree) === '...') {\n return visitor.ellipsis(tree as ts.SpreadElement, this);\n }\n return visitor.spreadElement(tree as ts.SpreadElement, this);\n case ts.SyntaxKind.ElementAccessExpression:\n return visitor.elementAccessExpression(tree as ts.ElementAccessExpression, this);\n case ts.SyntaxKind.TemplateExpression:\n return visitor.templateExpression(tree as ts.TemplateExpression, this);\n case ts.SyntaxKind.NonNullExpression:\n return visitor.nonNullExpression(tree as ts.NonNullExpression, this);\n case ts.SyntaxKind.ParenthesizedExpression:\n return visitor.parenthesizedExpression(tree as ts.ParenthesizedExpression, this);\n case ts.SyntaxKind.VoidExpression:\n return visitor.maskingVoidExpression(tree as ts.VoidExpression, this);\n case ts.SyntaxKind.JSDocComment:\n return visitor.jsDoc(tree as ts.JSDoc, this);\n default:\n if (ts.isToken(tree)) {\n return visitor.token(tree, this);\n }\n this.reportUnsupported(tree, undefined);\n }\n\n if (this.options.bestEffort !== false) {\n // When doing best-effort conversion and we don't understand the node type, just return the complete text of it as-is\n return new OTree([this.textOf(tree)]);\n }\n // Otherwise, show a placeholder indicating we don't recognize the type\n const nodeKind = ts.SyntaxKind[tree.kind];\n return new UnknownSyntax(\n [`<${nodeKind} ${this.textOf(tree)}>`],\n ['\\n', ...nodeChildren(tree).map(this.convert.bind(this))],\n {\n indent: 2,\n },\n );\n }\n\n /**\n * Attach any leading whitespace and comments to the given output tree\n *\n * Regardless of whether it's declared to be able to accept such or not.\n */\n private attachLeadingTrivia(node: ts.Node, transformed: OTree): OTree {\n // Add comments and leading whitespace\n const leadingRanges = scanText(this.sourceFile.text, node.getFullStart(), node.getStart(this.sourceFile));\n\n const precede: OTree[] = [];\n for (const range of leadingRanges) {\n let trivia: OTree | undefined = undefined;\n switch (range.type) {\n case 'other':\n trivia = new OTree([repeatNewlines(this.sourceFile.text.substring(range.pos, range.end))], [], {\n renderOnce: `ws-${range.pos}`,\n });\n break;\n case 'linecomment':\n case 'blockcomment':\n trivia = this.handler.commentRange(\n commentSyntaxFromCommentRange(commentRangeFromTextRange(range), this),\n this,\n );\n break;\n\n case 'directive':\n break;\n }\n if (trivia != null) {\n // Set spans on comments to make sure their visibility is toggled correctly.\n trivia.setSpan(range.pos, range.end);\n precede.push(trivia);\n }\n }\n\n // FIXME: No trailing comments for now, they're too tricky\n\n if (precede.length > 0 && !transformed.isEmpty) {\n return new OTree([...precede, transformed], [], { canBreakLine: true });\n }\n return transformed;\n }\n}\n\n/**\n * Interface for AST handlers\n *\n * C is the type of hierarchical context the handler uses. Context\n * needs 2 operations: a constructor for a default context, and a\n * merge operation to combine 2 contexts to yield a new one.\n *\n * Otherwise, the handler should return an OTree for every type\n * of AST node.\n */\nexport interface AstHandler<C> {\n readonly language: TargetLanguage;\n\n readonly defaultContext: C;\n readonly indentChar?: ' ' | '\\t';\n mergeContext(old: C, update: Partial<C>): C;\n\n sourceFile(node: ts.SourceFile, context: AstRenderer<C>): OTree;\n commentRange(node: CommentSyntax, context: AstRenderer<C>): OTree;\n importStatement(node: ImportStatement, context: AstRenderer<C>): OTree;\n stringLiteral(node: ts.StringLiteral | ts.NoSubstitutionTemplateLiteral, children: AstRenderer<C>): OTree;\n numericLiteral(node: ts.NumericLiteral, children: AstRenderer<C>): OTree;\n functionDeclaration(node: ts.FunctionDeclaration, children: AstRenderer<C>): OTree;\n identifier(node: ts.Identifier, children: AstRenderer<C>): OTree;\n block(node: ts.Block, children: AstRenderer<C>): OTree;\n parameterDeclaration(node: ts.ParameterDeclaration, children: AstRenderer<C>): OTree;\n returnStatement(node: ts.ReturnStatement, context: AstRenderer<C>): OTree;\n binaryExpression(node: ts.BinaryExpression, context: AstRenderer<C>): OTree;\n ifStatement(node: ts.IfStatement, context: AstRenderer<C>): OTree;\n propertyAccessExpression(\n node: ts.PropertyAccessExpression,\n context: AstRenderer<C>,\n submoduleReference: SubmoduleReference | undefined,\n ): OTree;\n awaitExpression(node: ts.AwaitExpression, context: AstRenderer<C>): OTree;\n callExpression(node: ts.CallExpression, context: AstRenderer<C>): OTree;\n expressionStatement(node: ts.ExpressionStatement, context: AstRenderer<C>): OTree;\n token<A extends ts.SyntaxKind>(node: ts.Token<A>, context: AstRenderer<C>): OTree;\n objectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree;\n newExpression(node: ts.NewExpression, context: AstRenderer<C>): OTree;\n propertyAssignment(node: ts.PropertyAssignment, context: AstRenderer<C>): OTree;\n variableStatement(node: ts.VariableStatement, context: AstRenderer<C>): OTree;\n variableDeclarationList(node: ts.VariableDeclarationList, context: AstRenderer<C>): OTree;\n variableDeclaration(node: ts.VariableDeclaration, context: AstRenderer<C>): OTree;\n jsDoc(node: ts.JSDoc, context: AstRenderer<C>): OTree;\n arrayLiteralExpression(node: ts.ArrayLiteralExpression, context: AstRenderer<C>): OTree;\n shorthandPropertyAssignment(node: ts.ShorthandPropertyAssignment, context: AstRenderer<C>): OTree;\n forOfStatement(node: ts.ForOfStatement, context: AstRenderer<C>): OTree;\n classDeclaration(node: ts.ClassDeclaration, context: AstRenderer<C>): OTree;\n constructorDeclaration(node: ts.ConstructorDeclaration, context: AstRenderer<C>): OTree;\n propertyDeclaration(node: ts.PropertyDeclaration, context: AstRenderer<C>): OTree;\n computedPropertyName(node: ts.Expression, context: AstRenderer<C>): OTree;\n methodDeclaration(node: ts.MethodDeclaration, context: AstRenderer<C>): OTree;\n interfaceDeclaration(node: ts.InterfaceDeclaration, context: AstRenderer<C>): OTree;\n propertySignature(node: ts.PropertySignature, context: AstRenderer<C>): OTree;\n methodSignature(node: ts.MethodSignature, context: AstRenderer<C>): OTree;\n asExpression(node: ts.AsExpression, context: AstRenderer<C>): OTree;\n prefixUnaryExpression(node: ts.PrefixUnaryExpression, context: AstRenderer<C>): OTree;\n spreadElement(node: ts.SpreadElement, context: AstRenderer<C>): OTree;\n spreadAssignment(node: ts.SpreadAssignment, context: AstRenderer<C>): OTree;\n templateExpression(node: ts.TemplateExpression, context: AstRenderer<C>): OTree;\n nonNullExpression(node: ts.NonNullExpression, context: AstRenderer<C>): OTree;\n parenthesizedExpression(node: ts.ParenthesizedExpression, context: AstRenderer<C>): OTree;\n maskingVoidExpression(node: ts.VoidExpression, context: AstRenderer<C>): OTree;\n elementAccessExpression(node: ts.ElementAccessExpression, context: AstRenderer<C>): OTree;\n\n // Not a node, called when we recognize a spread element/assignment that is only\n // '...' and nothing else.\n ellipsis(node: ts.SpreadElement | ts.SpreadAssignment, context: AstRenderer<C>): OTree;\n}\n\nexport function nimpl<C>(node: ts.Node, context: AstRenderer<C>, options: { additionalInfo?: string } = {}) {\n const children = nodeChildren(node).map((c) => context.convert(c));\n\n let syntaxKind = ts.SyntaxKind[node.kind];\n if (syntaxKind === 'FirstPunctuation') {\n // These have the same identifier but this name is more descriptive\n syntaxKind = 'OpenBraceToken';\n }\n\n const parts = [`(${syntaxKind}`];\n if (options.additionalInfo) {\n parts.push(`{${options.additionalInfo}}`);\n }\n parts.push(context.textOf(node));\n\n return new UnknownSyntax([parts.join(' ')], children.length > 0 ? ['\\n', ...children] : [], {\n indent: 2,\n suffix: ')',\n separator: '\\n',\n canBreakLine: true,\n });\n}\n\nexport interface AstRendererOptions {\n /**\n * If enabled, don't translate the text of unknown nodes\n *\n * @default true\n */\n bestEffort?: boolean;\n}\n\ninterface ClassifiedNode {\n node: ts.Node;\n visible: boolean;\n maskingVoid?: ts.VoidExpression;\n}\n\nfunction filterVisible(nodes: readonly ts.Node[]): ts.Node[] {\n return assignVisibility(nodes)\n .map((c) => (c.visible ? c.node : c.maskingVoid))\n .filter(notUndefined);\n}\n\nfunction assignVisibility(nodes: readonly ts.Node[]): ClassifiedNode[] {\n const ret: ClassifiedNode[] = [];\n\n let visible = true;\n for (const node of nodes) {\n const maskingVoid = extractMaskingVoidExpression(node);\n if (visible && maskingVoid) {\n visible = false;\n }\n\n ret.push({ node, maskingVoid, visible });\n\n if (!visible) {\n const showing = extractShowingVoidExpression(node);\n if (showing) {\n visible = true;\n }\n }\n }\n\n return ret;\n}\n\nfunction notUndefined<A>(x: A | undefined): x is A {\n return x !== undefined;\n}\n\n/**\n * Our own representation of comments\n *\n * (So we can synthesize 'em\n */\nexport interface CommentSyntax {\n pos: number;\n text: string;\n hasTrailingNewLine?: boolean;\n kind: ts.CommentKind;\n\n /**\n * Whether it's at the end of a code line (so we can render a separating space)\n */\n isTrailing?: boolean;\n}\n\nfunction commentSyntaxFromCommentRange(rng: ts.CommentRange, renderer: AstRenderer<any>): CommentSyntax {\n return {\n hasTrailingNewLine: rng.hasTrailingNewLine,\n kind: rng.kind,\n pos: rng.pos,\n text: renderer.textAt(rng.pos, rng.end),\n isTrailing: renderer.codeOnLineBefore(rng.pos),\n };\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rosetta-reader.js","sourceRoot":"","sources":["../src/rosetta-reader.ts"],"names":[],"mappings":";;;AAEA,kDAA+E;AAE/E,qCAAqC;AACrC,kDAAwD;AACxD,oEAAgE;AAChE,0FAAqF;AAErF,uCAMmB;AACnB,uCAA2C;AAC3C,+CAAgE;AAChE,2CAAyC;AACzC,iCAAoE;AAEpE,IAAY,kBAeX;AAfD,WAAY,kBAAkB;IAC5B;;OAEG;IACH,2CAAqB,CAAA;IAErB;;OAEG;IACH,6CAAuB,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,CACH,CAAC;IACJ,CAAC;IAEM,gBAAgB,CAAC,MAA6B;QACnD,IAAA,uBAAgB,EAAC,IAAI,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IAC7C,CAAC;IAED,IAAW,SAAS;QAClB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IACjD,CAAC;IAED,IAAY,UAAU;QACpB,OAAO,CAAC,GAAG,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClD,CAAC;IAED;;;OAGG;IACK,gBAAgB,CAAC,WAAoC,EAAE,gBAAyB;QACtF,IAAI,CAAC,gBAAgB,IAAI,WAAW,EAAE,UAAU,KAAK,KAAK,EAAE;YAC1D,OAAO,WAAW,CAAC;SACpB;QACD,MAAM,OAAO,GAAG,IAAA,mBAAY,EAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,UAAU,GAAG,gFAAgF,CAAC;QACpG,OAAO;YACL,GAAG,WAAW;YACd,MAAM,EAAE,GAAG,OAAO,IAAI,UAAU,KAAK,WAAW,CAAC,MAAM,EAAE;SAC1D,CAAC;IACJ,CAAC;CACF;AA5OD,kDA4OC;AAED,SAAS,EAAE,CAAC,CAAc;IACxB,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAa,OAAQ,SAAQ,mBAAmB;CAAG;AAAnD,0BAAmD","sourcesContent":["import * as spec from '@jsii/spec';\n\nimport { allTypeScriptSnippets, guessTabletLocation } from './jsii/assemblies';\nimport { TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { transformMarkdown } from './markdown/markdown';\nimport { MarkdownRenderer } from './markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from './markdown/replace-typescript-transform';\nimport { CodeBlock } from './markdown/types';\nimport {\n SnippetParameters,\n TypeScriptSnippet,\n updateParameters,\n ApiLocation,\n typeScriptSnippetFromSource,\n} from './snippet';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, Translation } from './tablets/tablets';\nimport { Translator } from './translate';\nimport { commentToken, pathExists, printDiagnostics } from './util';\n\nexport enum UnknownSnippetMode {\n /**\n * Return the snippet as given (untranslated)\n */\n VERBATIM = 'verbatim',\n\n /**\n * Live-translate the snippet as best as we can\n */\n TRANSLATE = 'translate',\n\n /**\n * Throw an error if this occurs\n */\n FAIL = 'fail',\n}\n\nexport interface RosettaOptions {\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.VERBATIM\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n\n /**\n * Target languages to use for live conversion\n *\n * @default All languages\n */\n readonly targetLanguages?: readonly TargetLanguage[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Whether this Rosetta should operate in \"loose\" mode, where missing literate\n * source files and missing fixtures are ignored instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Adds a disclaimer to start of snippet if it did not compile.\n *\n * @default false\n */\n readonly prefixDisclaimer?: boolean;\n}\n\n/**\n * Entry point class for consumers of Rosetta tablets (primarily: pacmak)\n *\n * Rosetta can work in one of two modes:\n *\n * 1. Live translation of snippets.\n * 2. Read translations from a pre-translated tablet (prepared using `jsii-rosetta extract` command).\n *\n * The second method affords more control over the precise circumstances of\n * sample compilation and is recommended, but the first method will do\n * when the second one is not necessary.\n */\nexport class RosettaTabletReader {\n /**\n * Newly translated samples\n *\n * In case live translation has been enabled, all samples that have been translated on-the-fly\n * are added to this tablet.\n */\n public readonly liveTablet = new LanguageTablet();\n\n private readonly loadedTablets: LanguageTablet[] = [];\n private readonly extractedSnippets = new Map<string, TypeScriptSnippet>();\n private readonly translator: Translator;\n private readonly loose: boolean;\n private readonly unknownSnippets: UnknownSnippetMode;\n private readonly _prefixDisclaimer: boolean;\n\n public constructor(private readonly options: RosettaOptions = {}) {\n this.loose = !!options.loose;\n this.unknownSnippets = options.unknownSnippets ?? UnknownSnippetMode.VERBATIM;\n this.translator = new Translator(options.includeCompilerDiagnostics ?? false);\n this._prefixDisclaimer = options.prefixDisclaimer ?? false;\n }\n\n /**\n * Diagnostics encountered while doing live translation\n */\n public get diagnostics() {\n return this.translator.diagnostics;\n }\n\n /**\n * Load a tablet as a source for translateable snippets\n *\n * Note: the snippets loaded from this tablet will NOT be validated for\n * their fingerprints or translator versions! If a matching snippet is found\n * in the tablet, it will always be returned, whether or not it is stale.\n */\n public async loadTabletFromFile(tabletFile: string) {\n const tablet = new LanguageTablet();\n await tablet.load(tabletFile);\n this.addTablet(tablet);\n }\n\n /**\n * Directly add a tablet to the list of tablets to load translations from\n */\n public addTablet(tablet: LanguageTablet) {\n this.loadedTablets.push(tablet);\n }\n\n /**\n * Add an assembly\n *\n * If a default tablet file is found in the assembly's directory, it will be\n * loaded (and assumed to contain a complete list of translated snippets for\n * this assembly already).\n *\n * Otherwise, if live conversion is enabled, the snippets in the assembly\n * become available for live translation later. This is necessary because we probably\n * need to fixturize snippets for successful compilation, and the information\n * pacmak sends our way later on is not going to be enough to do that.\n */\n public async addAssembly(assembly: spec.Assembly, assemblyDir: string) {\n const defaultTablet = guessTabletLocation(assemblyDir);\n if (await pathExists(defaultTablet)) {\n try {\n await this.loadTabletFromFile(defaultTablet);\n return;\n } catch (e: any) {\n logging.warn(`Error loading ${defaultTablet}: ${e.message}. Skipped.`);\n }\n }\n\n // Inventarize the snippets from this assembly, but only if there's a chance\n // we're going to need them.\n if (this.unknownSnippets === UnknownSnippetMode.TRANSLATE) {\n for (const tsnip of await allTypeScriptSnippets([{ assembly, directory: assemblyDir }], this.loose)) {\n this.extractedSnippets.set(snippetKey(tsnip), tsnip);\n }\n }\n }\n\n /**\n * Translate the given snippet for the given target language\n *\n * This will either:\n *\n * - Find an existing translation in a tablet and return that, if available.\n * - Otherwise, find a fixturized version of this snippet in an assembly that\n * was loaded beforehand, and translate it on-the-fly. Finding the fixture\n * will be based on the snippet key, which consists of a hash of the\n * visible source and the API location.\n * - Otherwise, translate the snippet as-is (without fixture information).\n *\n * This will do and store a full conversion of the given snippet, even if it only\n * returns one language. Subsequent retrievals for the same snippet in other\n * languages will reuse the translation from cache.\n *\n * If you are calling this for the side effect of adding translations to the live\n * tablet, you only need to do that for one language.\n */\n public translateSnippet(source: TypeScriptSnippet, targetLang: TargetLanguage): Translation | undefined {\n // Look for it in loaded tablets (or previous conversions)\n for (const tab of this.allTablets) {\n const ret = tab.lookup(source, targetLang);\n if (ret !== undefined) {\n return this.prefixDisclaimer(ret, this._prefixDisclaimer);\n }\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.VERBATIM) {\n return this.prefixDisclaimer(\n {\n language: targetLang,\n source: source.visibleSource,\n },\n this._prefixDisclaimer,\n );\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.FAIL) {\n const message = [\n 'The following snippet was not found in any of the loaded tablets:',\n source.visibleSource,\n `Location: ${JSON.stringify(source.location)}`,\n `Language: ${targetLang}`,\n ].join('\\n');\n throw new Error(message);\n }\n\n if (this.options.targetLanguages && !this.options.targetLanguages.includes(targetLang)) {\n throw new Error(\n `Rosetta configured for live conversion to ${this.options.targetLanguages.join(\n ', ',\n )}, but requested ${targetLang}`,\n );\n }\n\n // See if we can find a fixturized version of this snippet. If so, use that do the live\n // conversion.\n const extracted = this.extractedSnippets.get(snippetKey(source));\n if (extracted !== undefined) {\n const snippet = this.translator.translate(extracted, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n // Try to live-convert it as-is.\n const snippet = this.translator.translate(source, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n /**\n * Translate a snippet found in the \"@ example\" section of a jsii assembly\n *\n * Behaves exactly like `translateSnippet`, so see that method for documentation.\n */\n public translateExample(\n apiLocation: ApiLocation,\n example: string,\n targetLang: TargetLanguage,\n strict: boolean,\n compileDirectory = process.cwd(),\n ): Translation {\n const location = { api: apiLocation, field: { field: 'example' } } as const;\n\n const snippet = typeScriptSnippetFromSource(example, location, strict, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n });\n\n const translated = this.translateSnippet(snippet, targetLang);\n\n return translated ?? { language: 'typescript', source: example };\n }\n\n /**\n * Translate all TypeScript snippets found in a block of Markdown text\n *\n * For each snippet, behaves exactly like `translateSnippet`, so see that\n * method for documentation.\n */\n public translateSnippetsInMarkdown(\n apiLocation: ApiLocation,\n markdown: string,\n targetLang: TargetLanguage,\n strict: boolean,\n translationToCodeBlock: (x: Translation) => CodeBlock = id,\n compileDirectory = process.cwd(),\n ): string {\n return transformMarkdown(\n markdown,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(apiLocation, strict, (tsSnip) => {\n const translated = this.translateSnippet(\n updateParameters(tsSnip, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n }),\n targetLang,\n );\n if (!translated) {\n return undefined;\n }\n\n return translationToCodeBlock(translated);\n }),\n );\n }\n\n public printDiagnostics(stream: NodeJS.WritableStream) {\n printDiagnostics(this.diagnostics, stream);\n }\n\n public get hasErrors() {\n return this.diagnostics.some((d) => d.isError);\n }\n\n private get allTablets(): LanguageTablet[] {\n return [...this.loadedTablets, this.liveTablet];\n }\n\n /**\n * Adds a disclaimer to the front of the example if the prefixDisclaimer\n * flag is set and we know it does not compile.\n */\n private prefixDisclaimer(translation: Translation | undefined, prefixDisclaimer: boolean): Translation | undefined {\n if (!prefixDisclaimer || translation?.didCompile !== false) {\n return translation;\n }\n const comment = commentToken(translation.language);\n const disclaimer = 'Example automatically generated from non-compiling source. May contain errors.';\n return {\n ...translation,\n source: `${comment} ${disclaimer}\\n${translation.source}`,\n };\n }\n}\n\nfunction id(x: Translation) {\n return x;\n}\n\n/**\n * Backwards compatibility\n *\n * @deprecated use RosettaTabletReader instead\n */\nexport class Rosetta extends RosettaTabletReader {}\n"]}
|
|
@@ -67,7 +67,7 @@ export declare class RosettaTranslator {
|
|
|
67
67
|
translateAll(snippets: TypeScriptSnippet[], addToTablet?: boolean): Promise<TranslateAllResult>;
|
|
68
68
|
translateAll(snippets: TypeScriptSnippet[], options?: TranslateAllOptions): Promise<TranslateAllResult>;
|
|
69
69
|
}
|
|
70
|
-
export
|
|
70
|
+
export type CacheHit = {
|
|
71
71
|
readonly type: 'miss';
|
|
72
72
|
} | {
|
|
73
73
|
readonly type: 'hit';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.RosettaTranslator = void 0;
|
|
4
|
-
const
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
5
|
const fingerprinting_1 = require("./jsii/fingerprinting");
|
|
6
6
|
const languages_1 = require("./languages");
|
|
7
7
|
const logging = require("./logging");
|
|
@@ -131,7 +131,7 @@ class RosettaTranslator {
|
|
|
131
131
|
finally {
|
|
132
132
|
process.chdir(origDir);
|
|
133
133
|
if (cleanCompilationDir) {
|
|
134
|
-
await
|
|
134
|
+
await node_fs_1.promises.rm(compilationDirectory, { force: true, recursive: true });
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
137
|
const fingerprinted = result.translatedSnippets.map((snippet) => snippet.withFingerprint(this.fingerprinter.fingerprintAll(snippet.fqnsReferenced())));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rosetta-translator.js","sourceRoot":"","sources":["../src/rosetta-translator.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AAGzC,0DAA0D;AAC1D,2CAA+C;AAC/C,qCAAqC;AACrC,uCAA8D;AAC9D,iEAAwH;AACxH,uCAA2C;AAC3C,+CAAsE;AACtE,mDAAmE;AAoCnE;;;;;GAKG;AACH,MAAa,iBAAiB;IAc5B,YAAmB,UAAoC,EAAE;QAbzD;;;;W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CAAC,MAAM,CAAC,OAAO,CAAC,4BAAgB,CAAC,CAAC,KAAK,CAC7D,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,EAAE,OAAO,KAAK,UAAU,CAAC,OAAO,CAC/F,CAAC;IACF,MAAM,UAAU,GAAG,aAAa,CAAC,cAAc,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC,KAAK,SAAS,CAAC,OAAO,CAAC,eAAe,CAAC;IAClH,MAAM,iBAAiB,GAAG,YAAY,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC;IAExE,IAAI,WAAW,IAAI,eAAe,IAAI,UAAU,IAAI,iBAAiB,EAAE;QACrE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,UAAU,EAAE,iBAAiB,EAAE,CAAC;KAC/G;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC7D,CAAC;AAcD,SAAS,SAAS,CAAC,OAA0B;IAC3C,OAAO,OAAO,CAAC,UAAU,EAAE,OAAO,KAAK,SAAS,CAAC;AACnD,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport * as spec from '@jsii/spec';\n\nimport { TypeFingerprinter } from './jsii/fingerprinting';\nimport { TARGET_LANGUAGES } from './languages';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, completeSource } from './snippet';\nimport { collectDependencies, validateAvailableDependencies, prepareDependencyDirectory } from './snippet-dependencies';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, TranslatedSnippet } from './tablets/tablets';\nimport { translateAll, TranslateAllResult } from './translate_all';\n\nexport interface RosettaTranslatorOptions {\n /**\n * Assemblies to use for fingerprinting\n *\n * The set of assemblies here are used to invalidate the cache. Any types that are\n * used in snippets are looked up in this set of assemblies. If found, their type\n * information is fingerprinted and compared to the type information at the time\n * compilation of the cached sample. If different, this is considered to be a cache\n * miss.\n *\n * You must use the same set of assemblies when generating and reading the cache\n * file, otherwise the fingerprint is guaranteed to be different and the cache will\n * be useless (e.g. if you generate the cache WITH assembly information but\n * read it without, or vice versa).\n *\n * @default No assemblies.\n */\n readonly assemblies?: spec.Assembly[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Allow reading dirty translations from cache\n *\n * @default false\n */\n readonly allowDirtyTranslations?: boolean;\n}\n\n/**\n * Entry point for consumers that want to translate code on-the-fly\n *\n * If you want to generate and translate code on-the-fly, in ways that cannot\n * be achieved by the rosetta CLI, use this class.\n */\nexport class RosettaTranslator {\n /**\n * Tablet with fresh translations\n *\n * All new translations (not read from cache) are added to this tablet.\n */\n public readonly tablet = new LanguageTablet();\n\n public readonly cache = new LanguageTablet();\n\n private readonly fingerprinter: TypeFingerprinter;\n private readonly includeCompilerDiagnostics: boolean;\n private readonly allowDirtyTranslations: boolean;\n\n public constructor(options: RosettaTranslatorOptions = {}) {\n this.fingerprinter = new TypeFingerprinter(options?.assemblies ?? []);\n this.includeCompilerDiagnostics = options.includeCompilerDiagnostics ?? false;\n this.allowDirtyTranslations = options.allowDirtyTranslations ?? false;\n }\n\n /**\n * @deprecated use `addToCache` instead\n */\n public async loadCache(fileName: string) {\n try {\n await this.cache.load(fileName);\n } catch (e: any) {\n logging.warn(`Error reading cache ${fileName}: ${e.message}`);\n }\n }\n\n public async addToCache(filename: string) {\n const tab = await LanguageTablet.fromOptionalFile(filename);\n this.cache.addTablet(tab);\n }\n\n public addTabletsToCache(...tablets: LanguageTablet[]) {\n for (const tab of tablets) {\n this.cache.addTablet(tab);\n }\n }\n\n public hasCache() {\n return this.cache.count > 0;\n }\n\n /**\n * For all the given snippets, try to read translations from the cache\n *\n * Will remove the cached snippets from the input array.\n */\n public readFromCache(snippets: TypeScriptSnippet[], addToTablet = true, compiledOnly = false): ReadFromCacheResults {\n const translations = new Array<TranslatedSnippet>();\n const remaining = new Array<TypeScriptSnippet>();\n\n let infusedCount = 0;\n let dirtyCount = 0;\n let dirtySourceCount = 0;\n let dirtyTypesCount = 0;\n let dirtyTranslatorCount = 0;\n let dirtyDidntCompile = 0;\n\n for (const snippet of snippets) {\n const fromCache = tryReadFromCache(snippet, this.cache, this.fingerprinter, compiledOnly);\n switch (fromCache.type) {\n case 'hit':\n if (addToTablet) {\n this.tablet.addSnippet(fromCache.snippet);\n }\n translations.push(fromCache.snippet);\n\n infusedCount += fromCache.infused ? 1 : 0;\n break;\n\n case 'dirty':\n dirtyCount += 1;\n dirtySourceCount += fromCache.dirtySource ? 1 : 0;\n dirtyTranslatorCount += fromCache.dirtyTranslator ? 1 : 0;\n dirtyTypesCount += fromCache.dirtyTypes ? 1 : 0;\n dirtyDidntCompile += fromCache.dirtyDidntCompile ? 1 : 0;\n\n if (this.allowDirtyTranslations) {\n translations.push(fromCache.translation);\n } else {\n remaining.push(snippet);\n }\n break;\n\n case 'miss':\n remaining.push(snippet);\n break;\n }\n }\n\n return {\n translations,\n remaining,\n infusedCount,\n dirtyCount,\n dirtySourceCount,\n dirtyTranslatorCount,\n dirtyTypesCount,\n dirtyDidntCompile,\n };\n }\n\n public async translateAll(snippets: TypeScriptSnippet[], addToTablet?: boolean): Promise<TranslateAllResult>;\n public async translateAll(snippets: TypeScriptSnippet[], options?: TranslateAllOptions): Promise<TranslateAllResult>;\n public async translateAll(\n snippets: TypeScriptSnippet[],\n optionsOrAddToTablet?: boolean | TranslateAllOptions,\n ): Promise<TranslateAllResult> {\n const options =\n optionsOrAddToTablet && typeof optionsOrAddToTablet === 'object'\n ? optionsOrAddToTablet\n : { addToTablet: optionsOrAddToTablet };\n\n const exampleDependencies = collectDependencies(snippets);\n\n let compilationDirectory;\n let cleanCompilationDir = false;\n if (options?.compilationDirectory) {\n // If the user provided a directory, we're going to trust-but-confirm.\n await validateAvailableDependencies(options.compilationDirectory, exampleDependencies);\n compilationDirectory = options.compilationDirectory;\n } else {\n compilationDirectory = await prepareDependencyDirectory(exampleDependencies);\n cleanCompilationDir = true;\n }\n\n const origDir = process.cwd();\n // Easiest way to get a fixed working directory (for sources) in is to chdir\n process.chdir(compilationDirectory);\n\n let result;\n try {\n result = await translateAll(snippets, this.includeCompilerDiagnostics);\n } finally {\n process.chdir(origDir);\n if (cleanCompilationDir) {\n await fs.rm(compilationDirectory, { force: true, recursive: true });\n }\n }\n\n const fingerprinted = result.translatedSnippets.map((snippet) =>\n snippet.withFingerprint(this.fingerprinter.fingerprintAll(snippet.fqnsReferenced())),\n );\n\n if (options?.addToTablet ?? true) {\n for (const translation of fingerprinted) {\n this.tablet.addSnippet(translation);\n }\n }\n\n return {\n translatedSnippets: fingerprinted,\n diagnostics: result.diagnostics,\n };\n }\n}\n\n/**\n * Try to find the translation for the given snippet in the given cache\n *\n * Rules for cacheability are:\n * - id is the same (== visible source didn't change)\n * - complete source is the same (== fixture didn't change)\n * - all types involved have the same fingerprint (== API surface didn't change)\n * - the versions of all translations match the versions on the available translators (== translator itself didn't change)\n *\n * For the versions check: we could have selectively picked some translations\n * from the cache while performing others. However, since the big work is in\n * parsing the TypeScript, and the rendering itself is peanutes (assumption), it\n * doesn't really make a lot of difference. So, for simplification's sake,\n * we'll regen all translations if there's at least one that's outdated.\n */\nfunction tryReadFromCache(\n sourceSnippet: TypeScriptSnippet,\n cache: LanguageTablet,\n fingerprinter: TypeFingerprinter,\n compiledOnly: boolean,\n): CacheHit {\n const fromCache = cache.tryGetSnippet(snippetKey(sourceSnippet));\n\n if (!fromCache) {\n return { type: 'miss' };\n }\n\n // infused snippets won't pass the full source check or the fingerprinter\n // but there is no reason to try to recompile it, so return cached snippet\n // if there exists one.\n if (isInfused(sourceSnippet)) {\n return { type: 'hit', snippet: fromCache, infused: true };\n }\n\n const dirtySource = completeSource(sourceSnippet) !== fromCache.snippet.fullSource;\n const dirtyTranslator = !Object.entries(TARGET_LANGUAGES).every(\n ([lang, translator]) => fromCache.snippet.translations?.[lang]?.version === translator.version,\n );\n const dirtyTypes = fingerprinter.fingerprintAll(fromCache.fqnsReferenced()) !== fromCache.snippet.fqnsFingerprint;\n const dirtyDidntCompile = compiledOnly && !fromCache.snippet.didCompile;\n\n if (dirtySource || dirtyTranslator || dirtyTypes || dirtyDidntCompile) {\n return { type: 'dirty', translation: fromCache, dirtySource, dirtyTranslator, dirtyTypes, dirtyDidntCompile };\n }\n return { type: 'hit', snippet: fromCache, infused: false };\n}\n\nexport type CacheHit =\n | { readonly type: 'miss' }\n | { readonly type: 'hit'; readonly snippet: TranslatedSnippet; readonly infused: boolean }\n | {\n readonly type: 'dirty';\n readonly translation: TranslatedSnippet;\n readonly dirtySource: boolean;\n readonly dirtyTranslator: boolean;\n readonly dirtyTypes: boolean;\n readonly dirtyDidntCompile: boolean;\n };\n\nfunction isInfused(snippet: TypeScriptSnippet) {\n return snippet.parameters?.infused !== undefined;\n}\n\nexport interface ReadFromCacheResults {\n /**\n * Successful translations\n */\n readonly translations: TranslatedSnippet[];\n\n /**\n * Successful but dirty hits\n */\n readonly remaining: TypeScriptSnippet[];\n\n /**\n * How many successfully hit translations were infused\n */\n readonly infusedCount: number;\n\n readonly dirtyCount: number;\n\n // Counts for dirtiness (a single snippet may be dirty for more than one reason)\n readonly dirtySourceCount: number;\n readonly dirtyTranslatorCount: number;\n readonly dirtyTypesCount: number;\n readonly dirtyDidntCompile: number;\n}\n\nexport interface TranslateAllOptions {\n /**\n * @default - Create a temporary directory with all necessary packages\n */\n readonly compilationDirectory?: string;\n\n /**\n * @default true\n */\n readonly addToTablet?: boolean;\n}\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.prepareDependencyDirectory = exports.validateAvailableDependencies = exports.collectDependencies = void 0;
|
|
4
|
-
const cp = require("child_process");
|
|
4
|
+
const cp = require("node:child_process");
|
|
5
|
+
const node_fs_1 = require("node:fs");
|
|
6
|
+
const fs = require("node:fs");
|
|
7
|
+
const os = require("node:os");
|
|
8
|
+
const path = require("node:path");
|
|
5
9
|
const fastGlob = require("fast-glob");
|
|
6
|
-
const fs_1 = require("fs");
|
|
7
|
-
const fs = require("fs");
|
|
8
|
-
const os = require("os");
|
|
9
|
-
const path = require("path");
|
|
10
10
|
const semver = require("semver");
|
|
11
11
|
const semver_intersect_1 = require("semver-intersect");
|
|
12
12
|
const find_utils_1 = require("./find-utils");
|
|
@@ -90,7 +90,7 @@ async function prepareDependencyDirectory(deps) {
|
|
|
90
90
|
.filter(isConcrete)
|
|
91
91
|
.map((x) => x.resolvedDirectory);
|
|
92
92
|
const monorepoPackages = await scanMonoRepos(concreteDirs);
|
|
93
|
-
const tmpDir = await
|
|
93
|
+
const tmpDir = await node_fs_1.promises.mkdtemp(path.join(os.tmpdir(), 'rosetta'));
|
|
94
94
|
logging.info(`Preparing dependency closure at ${tmpDir}`);
|
|
95
95
|
// Resolved symbolic packages against monorepo
|
|
96
96
|
const resolvedDeps = (0, util_1.mkDict)(Object.entries(deps).map(([name, dep]) => [
|
|
@@ -119,8 +119,8 @@ async function prepareDependencyDirectory(deps) {
|
|
|
119
119
|
const target = path.join(modDir, name);
|
|
120
120
|
if (!(await (0, util_1.pathExists)(target))) {
|
|
121
121
|
// Package could be namespaced, so ensure the namespace dir exists
|
|
122
|
-
await
|
|
123
|
-
await
|
|
122
|
+
await node_fs_1.promises.mkdir(path.dirname(target), { recursive: true });
|
|
123
|
+
await node_fs_1.promises.symlink(source, target, 'dir');
|
|
124
124
|
}
|
|
125
125
|
}));
|
|
126
126
|
}
|
|
@@ -144,7 +144,7 @@ async function scanMonoRepos(startingDirs) {
|
|
|
144
144
|
const results = (0, util_1.mkDict)((await Promise.all(packageDirectories.map(async (directory) => {
|
|
145
145
|
const pjLocation = path.join(directory, 'package.json');
|
|
146
146
|
return (await (0, util_1.pathExists)(pjLocation))
|
|
147
|
-
? [[JSON.parse(await
|
|
147
|
+
? [[JSON.parse(await node_fs_1.promises.readFile(pjLocation, 'utf-8')).name, directory]]
|
|
148
148
|
: [];
|
|
149
149
|
}))).flat());
|
|
150
150
|
logging.debug(`Found ${Object.keys(results).length} packages in monorepo: ${(0, util_1.formatList)(Object.keys(results))}`);
|
|
@@ -155,16 +155,16 @@ async function findMonoRepoGlobs(startingDir) {
|
|
|
155
155
|
// Lerna monorepo
|
|
156
156
|
const lernaJsonDir = await (0, find_utils_1.findUp)(startingDir, async (dir) => (0, util_1.pathExists)(path.join(dir, 'lerna.json')));
|
|
157
157
|
if (lernaJsonDir) {
|
|
158
|
-
const lernaJson = JSON.parse(await
|
|
158
|
+
const lernaJson = JSON.parse(await node_fs_1.promises.readFile(path.join(lernaJsonDir, 'lerna.json'), 'utf-8'));
|
|
159
159
|
for (const glob of lernaJson?.packages ?? []) {
|
|
160
160
|
ret.add(path.join(lernaJsonDir, glob));
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
163
|
// Yarn monorepo
|
|
164
164
|
const yarnWsDir = await (0, find_utils_1.findUp)(startingDir, async (dir) => (await (0, util_1.pathExists)(path.join(dir, 'package.json'))) &&
|
|
165
|
-
JSON.parse(await
|
|
165
|
+
JSON.parse(await node_fs_1.promises.readFile(path.join(dir, 'package.json'), 'utf-8'))?.workspaces !== undefined);
|
|
166
166
|
if (yarnWsDir) {
|
|
167
|
-
const yarnWs = JSON.parse(await
|
|
167
|
+
const yarnWs = JSON.parse(await node_fs_1.promises.readFile(path.join(yarnWsDir, 'package.json'), 'utf-8'));
|
|
168
168
|
for (const glob of yarnWs.workspaces?.packages ?? []) {
|
|
169
169
|
ret.add(path.join(yarnWsDir, glob));
|
|
170
170
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snippet-dependencies.js","sourceRoot":"","sources":["../src/snippet-dependencies.ts"],"names":[],"mappings":";;;AAAA,yCA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AAA,iBAAU,EAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,CAAC,MAAM,kBAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,UAAU,KAAK,SAAS,CAC3G,CAAC;IACF,IAAI,SAAS,EAAE;QACb,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,kBAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;QACpG,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,UAAU,EAAE,QAAQ,IAAI,EAAE,EAAE;YACpD,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;SACrC;KACF;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,CAAwB;IAC1C,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC;AAC/B,CAAC;AAED,SAAS,UAAU,CAAC,CAAwB;IAC1C,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAI,EAAU,EAAE,EAAU;IAC1C,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE;QAClB,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;KACX;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;GAEG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import * as cp from 'node:child_process';\nimport { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as fastGlob from 'fast-glob';\nimport * as semver from 'semver';\nimport { intersect } from 'semver-intersect';\n\nimport { findDependencyDirectory, findUp } from './find-utils';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, CompilationDependency } from './snippet';\nimport { mkDict, formatList, pathExists } from './util';\n\n/**\n * Collect the dependencies of a bunch of snippets together in one declaration\n *\n * We assume here the dependencies will not conflict.\n */\nexport function collectDependencies(snippets: TypeScriptSnippet[]) {\n const ret: Record<string, CompilationDependency> = {};\n for (const snippet of snippets) {\n for (const [name, source] of Object.entries(snippet.compilationDependencies ?? {})) {\n ret[name] = resolveConflict(name, source, ret[name]);\n }\n }\n return ret;\n}\n\nfunction resolveConflict(\n name: string,\n a: CompilationDependency,\n b: CompilationDependency | undefined,\n): CompilationDependency {\n if (!b) {\n return a;\n }\n\n if (a.type === 'concrete' && b.type === 'concrete') {\n if (b.resolvedDirectory !== a.resolvedDirectory) {\n throw new Error(`Dependency conflict: ${name} can be either ${a.resolvedDirectory} or ${b.resolvedDirectory}`);\n }\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'symbolic') {\n // Intersect the ranges\n return {\n type: 'symbolic',\n versionRange: intersect(a.versionRange, b.versionRange),\n };\n }\n\n if (a.type === 'concrete' && b.type === 'symbolic') {\n const concreteVersion: string = JSON.parse(\n fs.readFileSync(path.join(a.resolvedDirectory, 'package.json'), 'utf-8'),\n ).version;\n\n if (!semver.satisfies(concreteVersion, b.versionRange)) {\n throw new Error(\n `Dependency conflict: ${name} expected to match ${b.versionRange} but found ${concreteVersion} at ${a.resolvedDirectory}`,\n );\n }\n\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'concrete') {\n // Reverse roles so we fall into the previous case\n return resolveConflict(name, b, a);\n }\n\n throw new Error('Cases should have been exhaustive');\n}\n\n/**\n * Check that the directory we were given has all the necessary dependencies in it\n *\n * It's a warning if this is not true, not an error.\n */\nexport async function validateAvailableDependencies(directory: string, deps: Record<string, CompilationDependency>) {\n const failures = await Promise.all(\n Object.entries(deps).flatMap(async ([name, _dep]) => {\n try {\n await findDependencyDirectory(name, directory);\n return [];\n } catch {\n return [name];\n }\n }),\n );\n\n if (failures.length > 0) {\n logging.warn(\n `${directory}: packages necessary to compile examples missing from supplied directory: ${failures.join(', ')}`,\n );\n }\n}\n\n/**\n * Prepare a temporary directory with symlinks to all the dependencies we need.\n *\n * - Symlinks the concrete dependencies\n * - Tries to first find the symbolic dependencies in a potential monorepo that might be present\n * (try both `lerna` and `yarn` monorepos).\n * - Installs the remaining symbolic dependencies using 'npm'.\n */\nexport async function prepareDependencyDirectory(deps: Record<string, CompilationDependency>): Promise<string> {\n const concreteDirs = Object.values(deps)\n .filter(isConcrete)\n .map((x) => x.resolvedDirectory);\n const monorepoPackages = await scanMonoRepos(concreteDirs);\n\n const tmpDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'rosetta'));\n logging.info(`Preparing dependency closure at ${tmpDir}`);\n\n // Resolved symbolic packages against monorepo\n const resolvedDeps = mkDict(\n Object.entries(deps).map(([name, dep]) => [\n name,\n dep.type === 'concrete'\n ? dep\n : ((monorepoPackages[name]\n ? { type: 'concrete', resolvedDirectory: monorepoPackages[name] }\n : dep) as CompilationDependency),\n ]),\n );\n\n // Use 'npm install' only for the symbolic packages. For the concrete packages,\n // npm is going to try and find transitive dependencies as well and it won't know\n // about monorepos.\n const symbolicInstalls = Object.entries(resolvedDeps).flatMap(([name, dep]) =>\n isSymbolic(dep) ? [`${name}@${dep.versionRange}`] : [],\n );\n const linkedInstalls = mkDict(\n Object.entries(resolvedDeps).flatMap(([name, dep]) =>\n isConcrete(dep) ? [[name, dep.resolvedDirectory] as const] : [],\n ),\n );\n\n // Run 'npm install' on it\n if (symbolicInstalls.length > 0) {\n logging.debug(`Installing example dependencies: ${symbolicInstalls.join(' ')}`);\n cp.execSync(`npm install ${symbolicInstalls.join(' ')}`, { cwd: tmpDir, encoding: 'utf-8' });\n }\n\n // Symlink the rest\n if (Object.keys(linkedInstalls).length > 0) {\n logging.debug(`Symlinking example dependencies: ${Object.values(linkedInstalls).join(' ')}`);\n const modDir = path.join(tmpDir, 'node_modules');\n await Promise.all(\n Object.entries(linkedInstalls).map(async ([name, source]) => {\n const target = path.join(modDir, name);\n if (!(await pathExists(target))) {\n // Package could be namespaced, so ensure the namespace dir exists\n await fsPromises.mkdir(path.dirname(target), { recursive: true });\n await fsPromises.symlink(source, target, 'dir');\n }\n }),\n );\n }\n\n return tmpDir;\n}\n\n/**\n * Map package name to directory\n */\nasync function scanMonoRepos(startingDirs: readonly string[]): Promise<Record<string, string>> {\n const globs = new Set<string>();\n for (const dir of startingDirs) {\n // eslint-disable-next-line no-await-in-loop\n setExtend(globs, await findMonoRepoGlobs(dir));\n }\n\n if (globs.size === 0) {\n return {};\n }\n\n logging.debug(`Monorepo package sources: ${Array.from(globs).join(', ')}`);\n\n const packageDirectories = await fastGlob(Array.from(globs).map(windowsToUnix), { onlyDirectories: true });\n const results = mkDict(\n (\n await Promise.all(\n packageDirectories.map(async (directory) => {\n const pjLocation = path.join(directory, 'package.json');\n return (await pathExists(pjLocation))\n ? [[JSON.parse(await fsPromises.readFile(pjLocation, 'utf-8')).name as string, directory] as const]\n : [];\n }),\n )\n ).flat(),\n );\n\n logging.debug(`Found ${Object.keys(results).length} packages in monorepo: ${formatList(Object.keys(results))}`);\n return results;\n}\n\nasync function findMonoRepoGlobs(startingDir: string): Promise<Set<string>> {\n const ret = new Set<string>();\n\n // Lerna monorepo\n const lernaJsonDir = await findUp(startingDir, async (dir) => pathExists(path.join(dir, 'lerna.json')));\n if (lernaJsonDir) {\n const lernaJson = JSON.parse(await fsPromises.readFile(path.join(lernaJsonDir, 'lerna.json'), 'utf-8'));\n for (const glob of lernaJson?.packages ?? []) {\n ret.add(path.join(lernaJsonDir, glob));\n }\n }\n\n // Yarn monorepo\n const yarnWsDir = await findUp(\n startingDir,\n async (dir) =>\n (await pathExists(path.join(dir, 'package.json'))) &&\n JSON.parse(await fsPromises.readFile(path.join(dir, 'package.json'), 'utf-8'))?.workspaces !== undefined,\n );\n if (yarnWsDir) {\n const yarnWs = JSON.parse(await fsPromises.readFile(path.join(yarnWsDir, 'package.json'), 'utf-8'));\n for (const glob of yarnWs.workspaces?.packages ?? []) {\n ret.add(path.join(yarnWsDir, glob));\n }\n }\n\n return ret;\n}\n\nfunction isSymbolic(x: CompilationDependency): x is Extract<CompilationDependency, { type: 'symbolic' }> {\n return x.type === 'symbolic';\n}\n\nfunction isConcrete(x: CompilationDependency): x is Extract<CompilationDependency, { type: 'concrete' }> {\n return x.type === 'concrete';\n}\n\nfunction setExtend<A>(xs: Set<A>, ys: Set<A>) {\n for (const y of ys) {\n xs.add(y);\n }\n return xs;\n}\n\n/**\n * Necessary for fastGlob\n */\nfunction windowsToUnix(x: string) {\n return x.replace(/\\\\/g, '/');\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TranslatedSnippet } from './tablets/tablets';
|
|
2
|
-
export
|
|
2
|
+
export type SnippetSelector = (snippets: TranslatedSnippet[]) => TranslatedSnippet;
|
|
3
3
|
/**
|
|
4
4
|
* Returns the longest available snippet.
|
|
5
5
|
*/
|
package/lib/snippet-selectors.js
CHANGED
|
@@ -42,10 +42,10 @@ function meanLength(snippets) {
|
|
|
42
42
|
if (snippets.length === 0) {
|
|
43
43
|
throw new Error('meanLength: array cannot be empty');
|
|
44
44
|
}
|
|
45
|
-
const
|
|
45
|
+
const meanLen = snippets.reduce((x, y) => x + y.originalSource.source.length, 0) / snippets.length;
|
|
46
46
|
const snippetScores = [];
|
|
47
47
|
for (const snippet of snippets) {
|
|
48
|
-
snippetScores.push({ snippet: snippet, score: Math.abs(snippet.originalSource.source.length -
|
|
48
|
+
snippetScores.push({ snippet: snippet, score: Math.abs(snippet.originalSource.source.length - meanLen) });
|
|
49
49
|
}
|
|
50
50
|
return getMinScore(snippetScores).snippet;
|
|
51
51
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sn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CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC1F,CAAC;AAED,SAAS,WAAW,CAAC,aAA6B;IAChD,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACnC,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,WAAW,CAAC,aAA6B;IAChD,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACnC,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { TranslatedSnippet } from './tablets/tablets';\n\nexport type SnippetSelector = (snippets: TranslatedSnippet[]) => TranslatedSnippet;\n\nclass SnippetScore {\n public constructor(public readonly snippet: TranslatedSnippet, public readonly score: number) {}\n}\n\n/**\n * Returns the longest available snippet.\n */\nexport function longest(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('longest: array cannot be empty');\n }\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: snippet.originalSource.source.length });\n }\n return getMaxScore(snippetScores).snippet;\n}\n\n/**\n * Returns the shortest available snippet.\n */\nexport function shortest(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('shortest: array cannot be empty');\n }\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: snippet.originalSource.source.length });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Returns the snippet with the length closest to the mean length of the available snippets.\n */\nexport function meanLength(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('meanLength: array cannot be empty');\n }\n\n const meanLen = snippets.reduce((x, y) => x + y.originalSource.source.length, 0) / snippets.length;\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: Math.abs(snippet.originalSource.source.length - meanLen) });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Finds and returns the mean sparse vector of available snippets for each type.\n */\nexport function mean(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('mean: array cannot be empty');\n }\n\n // Find mean counter.\n const counters: Array<Record<string, number>> = [];\n snippets.map((snippet) => {\n counters.push(snippet.snippet.syntaxKindCounter ?? {});\n });\n const meanCounter = findCenter(counters);\n // Find counter with closest euclidian distance.\n const snippetScores: SnippetScore[] = [];\n for (let i = 0; i < snippets.length; i++) {\n snippetScores.push({ snippet: snippets[i], score: euclideanDistance(meanCounter, counters[i]) });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Given a list of Records, outputs a Record that averages all the items in each Record.\n */\nfunction findCenter(counters: Array<Record<string, number>>): Record<string, number> {\n const centerCounter: Record<string, number> = {};\n for (const counter of counters) {\n for (const [key, value] of Object.entries(counter)) {\n centerCounter[key] = value + (centerCounter[key] ?? 0);\n }\n }\n const total = counters.length;\n Object.entries(centerCounter).map(([key, value]) => {\n centerCounter[key] = value / total;\n });\n return centerCounter;\n}\n\n/**\n * Finds the euclidean distance between two sparse vectors.\n * !!! This function assumes that the center parameter is a superset of the counter parameter. !!!\n */\nfunction euclideanDistance(center: Record<string, number>, counter: Record<string, number>): number {\n const individualDistances: number[] = [];\n Object.entries(center).map(([key, value]) => {\n individualDistances.push(value - (counter[key] ?? 0));\n });\n return individualDistances.reduce((acc, curr) => acc + Math.sqrt(Math.pow(curr, 2)), 0);\n}\n\nfunction getMaxScore(snippetScores: SnippetScore[]): SnippetScore {\n return snippetScores.reduce((x, y) => {\n return x.score >= y.score ? x : y;\n });\n}\n\nfunction getMinScore(snippetScores: SnippetScore[]): SnippetScore {\n return snippetScores.reduce((x, y) => {\n return x.score <= y.score ? x : y;\n });\n}\n"]}
|
package/lib/snippet.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export interface TypeScriptSnippet {
|
|
|
34
34
|
*/
|
|
35
35
|
readonly compilationDependencies?: Record<string, CompilationDependency>;
|
|
36
36
|
}
|
|
37
|
-
export
|
|
37
|
+
export type CompilationDependency = {
|
|
38
38
|
readonly type: 'concrete';
|
|
39
39
|
readonly resolvedDirectory: string;
|
|
40
40
|
} | {
|
|
@@ -69,7 +69,7 @@ export interface SnippetLocation {
|
|
|
69
69
|
* 'initializer-parameter' variant).
|
|
70
70
|
*/
|
|
71
71
|
export declare const INITIALIZER_METHOD_NAME = "<initializer>";
|
|
72
|
-
export
|
|
72
|
+
export type ApiLocation = {
|
|
73
73
|
readonly api: 'file';
|
|
74
74
|
readonly fileName: string;
|
|
75
75
|
} | {
|
|
@@ -91,7 +91,7 @@ export declare type ApiLocation = {
|
|
|
91
91
|
readonly methodName: string | typeof INITIALIZER_METHOD_NAME;
|
|
92
92
|
readonly parameterName: string;
|
|
93
93
|
};
|
|
94
|
-
export
|
|
94
|
+
export type FieldLocation = {
|
|
95
95
|
readonly field: 'markdown';
|
|
96
96
|
readonly line: number;
|
|
97
97
|
} | {
|
package/lib/snippet.js
CHANGED
|
@@ -94,11 +94,11 @@ exports.typeScriptSnippetFromSource = typeScriptSnippetFromSource;
|
|
|
94
94
|
*/
|
|
95
95
|
function typeScriptSnippetFromCompleteSource(typeScriptSource, location, strict, parameters = {}) {
|
|
96
96
|
const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);
|
|
97
|
-
const
|
|
98
|
-
const visibleSource = (0, visible_spans_1.trimCompleteSourceToVisible)(
|
|
97
|
+
const completeSrc = source.trimRight();
|
|
98
|
+
const visibleSource = (0, visible_spans_1.trimCompleteSourceToVisible)(completeSrc);
|
|
99
99
|
return {
|
|
100
100
|
visibleSource,
|
|
101
|
-
completeSource: visibleSource !==
|
|
101
|
+
completeSource: visibleSource !== completeSrc ? completeSrc : undefined,
|
|
102
102
|
location,
|
|
103
103
|
parameters: Object.assign({}, parameters, sourceParameters),
|
|
104
104
|
strict,
|
|
@@ -150,8 +150,8 @@ function parseKeyValueList(parameters) {
|
|
|
150
150
|
exports.parseKeyValueList = parseKeyValueList;
|
|
151
151
|
function parseMetadataLine(metadata) {
|
|
152
152
|
return parseKeyValueList(parseMetadata(metadata));
|
|
153
|
-
function parseMetadata(
|
|
154
|
-
return
|
|
153
|
+
function parseMetadata(md) {
|
|
154
|
+
return md
|
|
155
155
|
.trim()
|
|
156
156
|
.split(' ')
|
|
157
157
|
.map((s) => s.trim())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snippet.js","sourceRoot":"","sources":["../src/snippet.ts"],"names":[],"mappings":";;;AAAA,8DAAyE;AAuEzE;;;;;GAKG;AACU,QAAA,uBAAuB,GAAG,eAAe,CAAC;AAiBvD;;GAEG;AACH,SAAgB,cAAc,CAAC,QAAyB;IACtD,QAAQ,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE;QAC7B,KAAK,SAAS;YACZ,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC;QACtD,KAAK,UAAU;YACb,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;QACtE,KAAK,SAAS;YACZ,OAAO,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;KAC1C;AACH,CAAC;AATD,wCASC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,MAAmB;IACnD,QAAQ,MAAM,CAAC,GAAG,EAAE;QAClB,KAAK,MAAM;YACT,OAAO,MAAM,CAAC,QAAQ,CAAC;QACzB,KAAK,cAAc;YACjB,OAAO,GAAG,MAAM,CA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AAC,SAAS,CAAC;AACjC,CAAC;AAPD,gDAOC;AAED;;GAEG;AACH,IAAY,iBA+CX;AA/CD,WAAY,iBAAiB;IAC3B;;OAEG;IACH,wCAAmB,CAAA;IAEnB;;OAEG;IACH,6CAAwB,CAAA;IAExB;;;;;OAKG;IACH,4CAAuB,CAAA;IAEvB;;;;;;;;;;;OAWG;IACH,wCAAmB,CAAA;IAEnB;;;;OAIG;IACH,sDAAiC,CAAA;IAEjC;;;;;OAKG;IACH,4DAAuC,CAAA;AACzC,CAAC,EA/CW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QA+C5B","sourcesContent":["import { trimCompleteSourceToVisible } from './typescript/visible-spans';\n\n/**\n * A piece of TypeScript code found in an assembly, ready to be translated\n */\nexport interface TypeScriptSnippet {\n /**\n * The snippet code that ends up in the JSII assembly\n */\n readonly visibleSource: string;\n\n /**\n * Description of where the snippet was found\n */\n readonly location: SnippetLocation;\n\n /**\n * When enhanced with a fixture, the snippet's complete source code\n */\n readonly completeSource?: string;\n\n /**\n * Parameters for the conversion\n */\n readonly parameters?: Record<string, string>;\n\n /**\n * Whether this snippet must be processed as if `--strict` was always supplied.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * Dependencies necessary to compile this snippet\n *\n * Value is a regular { name -> semver } map like NPM's `dependencies`,\n * `devDependencies` etc.\n *\n * @default none\n */\n readonly compilationDependencies?: Record<string, CompilationDependency>;\n}\n\nexport type CompilationDependency =\n | { readonly type: 'concrete'; readonly resolvedDirectory: string }\n | { readonly type: 'symbolic'; readonly versionRange: string };\n\n/**\n * Description of a location where the snippet is found\n *\n * The location does not necessarily indicate an exact source file,\n * but it will generally refer to a location that can contain one or more\n * snippets.\n */\nexport interface SnippetLocation {\n /**\n * The jsii API with which this snippet is associated\n */\n readonly api: ApiLocation;\n\n /**\n * The API field in which the snippet is found, if any\n *\n * Absence of this field is appropriate for source files (or tests),\n * but for Markdown files 'field' should really be set to a Markdown\n * location.\n */\n readonly field?: FieldLocation;\n}\n\n/**\n * How to represent the initializer in a 'parameter' type.\n *\n * (Don't feel like making everyone's `case` statement worse by adding an\n * 'initializer-parameter' variant).\n */\nexport const INITIALIZER_METHOD_NAME = '<initializer>';\n\nexport type ApiLocation =\n | { readonly api: 'file'; readonly fileName: string }\n | { readonly api: 'moduleReadme'; readonly moduleFqn: string }\n | { readonly api: 'type'; readonly fqn: string }\n | { readonly api: 'initializer'; readonly fqn: string }\n | { readonly api: 'member'; readonly fqn: string; readonly memberName: string }\n | {\n readonly api: 'parameter';\n readonly fqn: string;\n readonly methodName: string | typeof INITIALIZER_METHOD_NAME;\n readonly parameterName: string;\n };\n\nexport type FieldLocation = { readonly field: 'markdown'; readonly line: number } | { readonly field: 'example' };\n\n/**\n * Render an API location to a human readable representation\n */\nexport function formatLocation(location: SnippetLocation): string {\n switch (location.field?.field) {\n case 'example':\n return `${renderApiLocation(location.api)}-example`;\n case 'markdown':\n return `${renderApiLocation(location.api)}-L${location.field.line}`;\n case undefined:\n return renderApiLocation(location.api);\n }\n}\n\n/**\n * Render an API location to an unique string\n *\n * This function is used in hashing examples for reuse, and so the formatting\n * here should not be changed lightly.\n */\nexport function renderApiLocation(apiLoc: ApiLocation): string {\n switch (apiLoc.api) {\n case 'file':\n return apiLoc.fileName;\n case 'moduleReadme':\n return `${apiLoc.moduleFqn}-README`;\n case 'type':\n return apiLoc.fqn;\n case 'initializer':\n return `${apiLoc.fqn}#initializer`;\n case 'member':\n return `${apiLoc.fqn}#${apiLoc.memberName}`;\n case 'parameter':\n return `${apiLoc.fqn}#${apiLoc.methodName}!#${apiLoc.parameterName}`;\n }\n}\n\n/**\n * Construct a TypeScript snippet from visible source\n *\n * Will parse parameters from a directive in the given source, but will not\n * interpret `/// !show` and `/// !hide` directives.\n *\n * `/// !show` and `/// !hide` directives WILL affect what gets displayed by\n * the translator, but they will NOT affect the snippet's cache key (i.e. the\n * cache key will be based on the full source given here).\n *\n * Use this if you are looking up a snippet in a tablet, which has been translated\n * previously using a fixture.\n */\nexport function typeScriptSnippetFromVisibleSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const visibleSource = source.trimRight();\n\n return {\n visibleSource,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\n/**\n * Construct a TypeScript snippet from literal source\n *\n * @deprecated Use `typeScriptSnippetFromVisibleSource`\n */\nexport function typeScriptSnippetFromSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n return typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters);\n}\n\n/**\n * Construct a TypeScript snippet from complete source\n *\n * Will parse parameters from a directive in the given source, and will\n * interpret `/// !show` and `/// !hide` directives.\n *\n * The snippet's cache key will be based on the source that remains after\n * these directives are processed.\n *\n * Use this if you are building a snippet to be translated, and take care\n * to store the return object's `visibleSource` in the assembly (not the original\n * source you passed in).\n */\nexport function typeScriptSnippetFromCompleteSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const completeSrc = source.trimRight();\n\n const visibleSource = trimCompleteSourceToVisible(completeSrc);\n\n return {\n visibleSource,\n completeSource: visibleSource !== completeSrc ? completeSrc : undefined,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\nexport function updateParameters(snippet: TypeScriptSnippet, params: Record<string, string>): TypeScriptSnippet {\n return {\n ...snippet,\n parameters: Object.assign(Object.create(null), snippet.parameters ?? {}, params),\n };\n}\n\n/**\n * Get the complete (compilable) source of a snippet\n */\nexport function completeSource(snippet: TypeScriptSnippet) {\n return snippet.completeSource ?? snippet.visibleSource;\n}\n\n/**\n * Extract snippet parameters from the first line of the source if it's a compiler directive\n */\nfunction parametersFromSourceDirectives(source: string): [string, Record<string, string>] {\n const [firstLine, ...rest] = source.split('\\n');\n // Also extract parameters from an initial line starting with '/// ' (getting rid of that line).\n const m = /[/]{3}(.*)$/.exec(firstLine);\n if (m) {\n return [rest.join('\\n'), parseMetadataLine(m[1])];\n }\n\n return [source, {}];\n}\n\n/**\n * Parse a set of 'param param=value' directives into an object\n */\nexport function parseKeyValueList(parameters: string[]): Record<string, string> {\n const ret: Record<string, string> = {};\n for (const param of parameters) {\n const parts = param.split('=', 2);\n if (parts.length === 2) {\n ret[parts[0]] = parts[1];\n } else {\n ret[parts[0]] = '';\n }\n }\n return ret;\n}\n\nexport function parseMetadataLine(metadata: string): Record<string, string> {\n return parseKeyValueList(parseMetadata(metadata));\n\n function parseMetadata(md: string): string[] {\n return md\n .trim()\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n }\n}\n\nexport function renderMetadataline(metadata: Record<string, string> = {}): string | undefined {\n const line = Object.entries(metadata)\n .filter(([key, _]) => !key.startsWith('$'))\n .map(([key, value]) => (value !== '' ? `${key}=${value}` : key))\n .join(' ');\n\n return line ? line : undefined;\n}\n\n/**\n * Recognized snippet parameters\n */\nexport enum SnippetParameters {\n /**\n * Use fixture with the given name (author parameter)\n */\n FIXTURE = 'fixture',\n\n /**\n * Don't use a fixture (author parameter)\n */\n NO_FIXTURE = 'nofixture',\n\n /**\n * Snippet was extracted from this literate file (backwards compatibility)\n *\n * Parameter attached by 'jsii'; load the given file instead of any fixture,\n * process as usual.\n */\n LITERATE_SOURCE = 'lit',\n\n /**\n * This snippet has been infused\n *\n * This means it has been copied from a different location, and potentially\n * even from a different assembly. If so, we can't expect it to compile in\n * the future, and if doesn't, we ignore the errors.\n *\n * N.B: this shouldn't make a difference in normal operation, as the `infuse`\n * command will duplicate the translation to the target tablet. This only\n * matters if we remove the tablet and try to re-extract an assembly with\n * infused examples from somewher else.\n */\n INFUSED = 'infused',\n\n /**\n * What directory to resolve fixtures in for this snippet (system parameter)\n *\n * Attached during processing, should not be used by authors.\n */\n $PROJECT_DIRECTORY = '$directory',\n\n /**\n * What directory to pretend the file is in (system parameter)\n *\n * Attached when compiling a literate file, as they compile in\n * the location where they are stored.\n */\n $COMPILATION_DIRECTORY = '$compilation',\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"strict.js","sourceRoot":"","sources":["../src/strict.ts"],"names":[],"mappings":";;;AAEA,SAAgB,kBAAkB,CAAC,QAAkB;IACnD,OAAO,CAAC,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC;AACpD,CAAC;AAFD,gDAEC","sourcesContent":["import { Assembly } from '@jsii/spec';\n\nexport function enforcesStrictMode(assembly: Assembly): boolean {\n return !!assembly.metadata?.jsii?.rosetta?.strict;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as ts from 'typescript';
|
|
2
|
-
export
|
|
2
|
+
export type SubmoduleReferenceMap = ReadonlyMap<ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier, SubmoduleReference>;
|
|
3
3
|
export declare class SubmoduleReference {
|
|
4
4
|
readonly root: ts.Symbol;
|
|
5
5
|
readonly submoduleChain: ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier;
|
|
@@ -3,11 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.SubmoduleReference = void 0;
|
|
4
4
|
const ts = require("typescript");
|
|
5
5
|
class SubmoduleReference {
|
|
6
|
-
constructor(root, submoduleChain, path) {
|
|
7
|
-
this.root = root;
|
|
8
|
-
this.submoduleChain = submoduleChain;
|
|
9
|
-
this.path = path;
|
|
10
|
-
}
|
|
11
6
|
static inSourceFile(sourceFile, typeChecker) {
|
|
12
7
|
const importDeclarations = sourceFile.statements
|
|
13
8
|
.filter((stmt) => ts.isImportDeclaration(stmt))
|
|
@@ -44,6 +39,11 @@ class SubmoduleReference {
|
|
|
44
39
|
}
|
|
45
40
|
return map;
|
|
46
41
|
}
|
|
42
|
+
constructor(root, submoduleChain, path) {
|
|
43
|
+
this.root = root;
|
|
44
|
+
this.submoduleChain = submoduleChain;
|
|
45
|
+
this.path = path;
|
|
46
|
+
}
|
|
47
47
|
get lastNode() {
|
|
48
48
|
if (this.path.length === 0) {
|
|
49
49
|
const node = this.root.valueDeclaration ?? this.root.declarations[0];
|
|
@@ -84,19 +84,19 @@ function importedSymbolsFrom(decl, sourceFile, typeChecker) {
|
|
|
84
84
|
}
|
|
85
85
|
if (namedBindings != null) {
|
|
86
86
|
if (ts.isNamespaceImport(namedBindings)) {
|
|
87
|
-
const { name } = namedBindings;
|
|
88
|
-
const symbol = typeChecker.getSymbolAtLocation(
|
|
87
|
+
const { name: bindingName } = namedBindings;
|
|
88
|
+
const symbol = typeChecker.getSymbolAtLocation(bindingName);
|
|
89
89
|
if (symbol == null) {
|
|
90
|
-
throw new Error(`No symbol was defined for node ${
|
|
90
|
+
throw new Error(`No symbol was defined for node ${bindingName.getText(sourceFile)}`);
|
|
91
91
|
}
|
|
92
92
|
imports.push(symbol);
|
|
93
93
|
}
|
|
94
94
|
else {
|
|
95
95
|
for (const specifier of namedBindings.elements) {
|
|
96
|
-
const { name } = specifier;
|
|
97
|
-
const symbol = typeChecker.getSymbolAtLocation(
|
|
96
|
+
const { name: specifierName } = specifier;
|
|
97
|
+
const symbol = typeChecker.getSymbolAtLocation(specifierName);
|
|
98
98
|
if (symbol == null) {
|
|
99
|
-
throw new Error(`No symbol was defined for node ${
|
|
99
|
+
throw new Error(`No symbol was defined for node ${specifierName.getText(sourceFile)}`);
|
|
100
100
|
}
|
|
101
101
|
imports.push(symbol);
|
|
102
102
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"submodule-reference.js","sourceRoot":"","sources":["../src/submodule-reference.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAOjC,MAAa,kBAAk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;IACrD,IAAI,MAAM,IAAI,IAAI,EAAE;QAClB,OAAO,CACL,MAAM,CAAC,YAAa,CAAC,MAAM,GAAG,CAAC;YAC/B,MAAM,CAAC,YAAa,CAAC,KAAK,CACxB,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,CACnG,CACF,CAAC;KACH;IAED,2EAA2E;IAC3E,qBAAqB;IACrB,OAAO,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzC,CAAC;AAED,SAAS,mBAAmB,CAAC,IAAY;IACvC,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["import * as ts from 'typescript';\n\nexport type SubmoduleReferenceMap = ReadonlyMap<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n>;\n\nexport class SubmoduleReference {\n public static inSourceFile(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker): SubmoduleReferenceMap {\n const importDeclarations = sourceFile.statements\n .filter((stmt) => ts.isImportDeclaration(stmt))\n .flatMap((stmt) => importedSymbolsFrom(stmt as ts.ImportDeclaration, sourceFile, typeChecker));\n\n return SubmoduleReference.inNode(sourceFile, typeChecker, new Set(importDeclarations));\n }\n\n private static inNode(\n node: ts.Node,\n typeChecker: ts.TypeChecker,\n importDeclarations: ReadonlySet<ts.Symbol>,\n map = new Map<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n >(),\n ): Map<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n > {\n if (ts.isPropertyAccessExpression(node)) {\n const [head, ...tail] = propertyPath(node);\n const symbol = typeChecker.getSymbolAtLocation(head.name);\n if (symbol && importDeclarations.has(symbol)) {\n // This is a reference within an imported namespace, so we need to record that...\n const firstNonNamespace = tail.findIndex((item) => !isLikelyNamespace(item.name, typeChecker));\n if (firstNonNamespace < 0) {\n map.set(node.expression, new SubmoduleReference(symbol, node.expression, []));\n } else {\n const tailEnd = tail[firstNonNamespace].expression;\n const path = tail.slice(0, firstNonNamespace).map((item) => item.name);\n map.set(tailEnd, new SubmoduleReference(symbol, tailEnd, path));\n }\n }\n\n return map;\n }\n\n // Faster than ||-ing a bung of if statements to avoid traversing uninteresting nodes...\n switch (node.kind) {\n case ts.SyntaxKind.ImportDeclaration:\n case ts.SyntaxKind.ExportDeclaration:\n break;\n default:\n for (const child of node.getChildren()) {\n map = SubmoduleReference.inNode(child, typeChecker, importDeclarations, map);\n }\n }\n\n return map;\n }\n\n private constructor(\n public readonly root: ts.Symbol,\n public readonly submoduleChain: ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n public readonly path: readonly ts.Node[],\n ) {}\n\n public get lastNode(): ts.Node {\n if (this.path.length === 0) {\n const node = this.root.valueDeclaration ?? this.root.declarations![0];\n return ts.isNamespaceImport(node) || ts.isImportSpecifier(node) ? node.name : node;\n }\n return this.path[this.path.length - 1];\n }\n\n public toString(): string {\n return `${this.constructor.name}<root=${this.root.name}, path=${JSON.stringify(\n this.path.map((item) => item.getText(item.getSourceFile())),\n )}>`;\n }\n}\n\n/**\n * Determines what symbols are imported by the given TypeScript import\n * delcaration, in the context of the specified file, using the provided type\n * checker.\n *\n * @param decl an import declaration.\n * @param sourceFile the source file that contains the import declaration.\n * @param typeChecker a TypeChecker instance valid for the provided source file.\n *\n * @returns the (possibly empty) list of symbols imported by this declaration.\n */\nfunction importedSymbolsFrom(\n decl: ts.ImportDeclaration,\n sourceFile: ts.SourceFile,\n typeChecker: ts.TypeChecker,\n): ts.Symbol[] {\n const { importClause } = decl;\n\n if (importClause == null) {\n // This is a \"for side effects\" import, which isn't relevant for our business here...\n return [];\n }\n\n const { name, namedBindings } = importClause;\n const imports = new Array<ts.Symbol>();\n\n if (name != null) {\n const symbol = typeChecker.getSymbolAtLocation(name);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${name.getText(sourceFile)}`);\n }\n imports.push(symbol);\n }\n if (namedBindings != null) {\n if (ts.isNamespaceImport(namedBindings)) {\n const { name: bindingName } = namedBindings;\n const symbol = typeChecker.getSymbolAtLocation(bindingName);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${bindingName.getText(sourceFile)}`);\n }\n imports.push(symbol);\n } else {\n for (const specifier of namedBindings.elements) {\n const { name: specifierName } = specifier;\n const symbol = typeChecker.getSymbolAtLocation(specifierName);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${specifierName.getText(sourceFile)}`);\n }\n imports.push(symbol);\n }\n }\n }\n\n return imports;\n}\n\ninterface PathEntry {\n readonly name: ts.Identifier | ts.PrivateIdentifier | ts.LeftHandSideExpression;\n readonly expression: ts.LeftHandSideExpression;\n}\n\nfunction propertyPath(node: ts.PropertyAccessExpression): readonly PathEntry[] {\n const { expression, name } = node;\n if (!ts.isPropertyAccessExpression(expression)) {\n return [\n { name: expression, expression },\n { name, expression },\n ];\n }\n return [...propertyPath(expression), { name, expression }];\n}\n\n/**\n * A heuristic to determine whether the provided node likely refers to some\n * namespace.\n *\n * @param node the node to be checked.\n * @param typeChecker a type checker that can obtain symbols for this node.\n *\n * @returns true if the node likely refers to a namespace name.\n */\nfunction isLikelyNamespace(node: ts.Node, typeChecker: ts.TypeChecker): boolean {\n if (!ts.isIdentifier(node)) {\n return false;\n }\n\n // If the identifier was bound to a symbol, we can inspect the declarations of\n // it to validate they are all module or namespace declarations.\n const symbol = typeChecker.getSymbolAtLocation(node);\n if (symbol != null) {\n return (\n symbol.declarations!.length > 0 &&\n symbol.declarations!.every(\n (decl) => ts.isModuleDeclaration(decl) || ts.isNamespaceExport(decl) || ts.isNamespaceImport(decl),\n )\n );\n }\n\n // We understand this is likely a namespace if the name does not start with\n // upper-case letter.\n return !startsWithUpperCase(node.text);\n}\n\nfunction startsWithUpperCase(text: string): boolean {\n return text.length > 0 && text[0] === text[0].toUpperCase();\n}\n"]}
|
package/lib/tablets/key.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.snippetKey = void 0;
|
|
4
|
-
const crypto = require("crypto");
|
|
5
|
-
const
|
|
4
|
+
const crypto = require("node:crypto");
|
|
5
|
+
const record_references_version_1 = require("../languages/record-references-version");
|
|
6
6
|
const snippet_1 = require("../snippet");
|
|
7
7
|
/**
|
|
8
8
|
* Determine the key for a code block
|
|
9
9
|
*/
|
|
10
10
|
function snippetKey(snippet) {
|
|
11
11
|
const h = crypto.createHash('sha256');
|
|
12
|
-
h.update(String(
|
|
12
|
+
h.update(String(record_references_version_1.RECORD_REFERENCES_VERSION));
|
|
13
13
|
// Mix in API location to distinguish between similar snippets
|
|
14
14
|
h.update((0, snippet_1.renderApiLocation)(snippet.location.api));
|
|
15
15
|
h.update(':');
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"key.js","sourceRoot":"","sources":["../../src/tablets/key.ts"],"names":[],"mappings":";;;AAAA,sCAAsC;AAEtC,sFAAmF;AACnF,wCAAkE;AAElE;;GAEG;AACH,SAAgB,UAAU,CAAC,OAA0B;IACnD,MAAM,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;IACtC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,qDAAyB,CAAC,CAAC,CAAC;IAC5C,8DAA8D;IAC9D,CAAC,CAAC,MAAM,CAAC,IAAA,2BAAiB,EAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IAClD,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACd,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;IAChC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC;AARD,gCAQC","sourcesContent":["import * as crypto from 'node:crypto';\n\nimport { RECORD_REFERENCES_VERSION } from '../languages/record-references-version';\nimport { TypeScriptSnippet, renderApiLocation } from '../snippet';\n\n/**\n * Determine the key for a code block\n */\nexport function snippetKey(snippet: TypeScriptSnippet) {\n const h = crypto.createHash('sha256');\n h.update(String(RECORD_REFERENCES_VERSION));\n // Mix in API location to distinguish between similar snippets\n h.update(renderApiLocation(snippet.location.api));\n h.update(':');\n h.update(snippet.visibleSource);\n return h.digest('hex');\n}\n"]}
|