Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 72 additions & 4 deletions tsc/internal/transformers/declarations/transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,14 @@ func (tx *DeclarationTransformer) transformTypeParameterDeclaration(input *ast.T

func (tx *DeclarationTransformer) transformVariableDeclaration(input *ast.VariableDeclaration) *ast.Node {
if tx.state.currentSourceFile.CommonJSModuleIndicator != nil && ast.IsVariableDeclarationInitializedToRequire(input.AsNode()) {
return tx.transformCjsRequireVariableDeclaration(input)
if canTransformCjsRequireToImport(input.AsNode()) {
return tx.transformCjsRequireVariableDeclaration(input)
}
// bindings with dynamic property names can't be named imports, so declare those and any nested or rest
// bindings with their types; the remaining bindings are imported by transformVariableStatement
return tx.recreateBindingElements(core.Filter(input.Name().AsBindingPattern().Elements.Nodes, func(elem *ast.Node) bool {
return !isCjsRequireImportableBinding(elem)
}))
}
if ast.IsBindingPattern(input.Name()) && hasAnyBindingInitializers(input.Name().AsBindingPattern()) {
return tx.recreateBindingPattern(input.Name().AsBindingPattern())
Expand Down Expand Up @@ -868,6 +875,24 @@ func hasAnyBindingInitializers(bindingPattern *ast.BindingPattern) bool {
return false
}

func canTransformCjsRequireToImport(decl *ast.Node) bool {
name := decl.Name()
if !ast.IsObjectBindingPattern(name) {
return true
}
for _, elem := range name.AsBindingPattern().Elements.Nodes {
if propertyName := elem.PropertyName(); propertyName != nil && ast.IsDynamicName(propertyName) {
return false
}
}
return true
}

func isCjsRequireImportableBinding(elem *ast.Node) bool {
propertyName := elem.PropertyName()
return ast.IsIdentifier(elem.Name()) && elem.AsBindingElement().DotDotDotToken == nil && (propertyName == nil || !ast.IsDynamicName(propertyName))
}

func (tx *DeclarationTransformer) transformCjsRequireVariableDeclaration(input *ast.VariableDeclaration) *ast.Node {
specifier := tx.rewriteModuleSpecifier(input.AsNode(), input.Initializer.AsCallExpression().Arguments.Nodes[0])
if ast.IsIdentifier(input.Name()) {
Expand All @@ -880,12 +905,33 @@ func (tx *DeclarationTransformer) transformCjsRequireVariableDeclaration(input *

// `const {x, y: z} = require("something")` -> `import {x, y as z} from "something"`
b := input.Name().AsBindingPattern()
importsAllBindings := canTransformCjsRequireToImport(input.AsNode())
var importSpecifiers []*ast.Node
for _, elem := range b.Elements.Nodes {
if !ast.IsIdentifier(elem.Name()) {
continue // nested destructuring, bail
}
importSpecifiers = append(importSpecifiers, tx.Factory().NewImportSpecifier(false, elem.PropertyName(), elem.Name()))
if !importsAllBindings && !isCjsRequireImportableBinding(elem) {
continue // declared as a variable by transformVariableDeclaration
}
propertyName := elem.PropertyName()
if propertyName != nil && !ast.IsIdentifier(propertyName) && !ast.IsStringLiteral(propertyName) {
// numeric and literal computed keys aren't valid import names, so normalize them to an identifier or string
text := ast.GetPropertyNameForPropertyNameNode(propertyName)
if ast.IsComputedPropertyName(propertyName) && ast.IsSignedNumericLiteral(propertyName.Expression()) {
// the property key is the string form of the number, so `[-0]` names property "0"
text = jsnum.FromString(text).String()
}
if scanner.IsIdentifierText(text, core.LanguageVariantStandard) {
propertyName = tx.Factory().NewIdentifier(text)
} else {
propertyName = tx.Factory().NewStringLiteral(text, ast.TokenFlagsNone)
}
}
importSpecifiers = append(importSpecifiers, tx.Factory().NewImportSpecifier(false, propertyName, elem.Name()))
}
if !importsAllBindings && len(importSpecifiers) == 0 {
return nil
}
return tx.Factory().NewImportDeclaration(
nil,
Expand All @@ -901,8 +947,12 @@ func (tx *DeclarationTransformer) transformCjsRequireVariableDeclaration(input *
}

func (tx *DeclarationTransformer) recreateBindingPattern(input *ast.BindingPattern) *ast.Node {
return tx.recreateBindingElements(input.Elements.Nodes)
}

func (tx *DeclarationTransformer) recreateBindingElements(elements []*ast.Node) *ast.Node {
var results []*ast.Node
for _, elem := range input.Elements.Nodes {
for _, elem := range elements {
result := tx.recreateBindingElement(elem.AsBindingElement())
if result == nil {
continue
Expand Down Expand Up @@ -2258,15 +2308,29 @@ func (tx *DeclarationTransformer) transformVariableStatement(input *ast.Variable
if tx.state.currentSourceFile.CommonJSModuleIndicator != nil {
var normalDeclarations []*ast.Node
var imports []*ast.Node
var partialImports []*ast.Node
for _, n := range inputNodes {
if ast.IsVariableDeclarationInitializedToRequire(n) {
if !ast.IsVariableDeclarationInitializedToRequire(n) {
normalDeclarations = append(normalDeclarations, n)
} else if canTransformCjsRequireToImport(n) {
imports = append(imports, n)
} else {
// dynamic, nested and rest bindings are declared as variables, and static identifier bindings are imported
normalDeclarations = append(normalDeclarations, n)
partialImports = append(partialImports, n)
}
}
inputNodes = normalDeclarations
extraImports, _ = tx.Visitor().VisitSlice(imports)
for _, n := range partialImports {
// match visitDeclarationSubtree's @internal and visibility checks
if tx.shouldStripInternal(n) || isDeclarationAndNotVisible(tx.EmitContext(), tx.resolver, n) {
continue
}
if imp := tx.transformCjsRequireVariableDeclaration(n.AsVariableDeclaration()); imp != nil {
extraImports = append(extraImports, imp)
}
}
}

nodes, _ := tx.Visitor().VisitSlice(inputNodes)
Expand Down Expand Up @@ -2684,6 +2748,10 @@ func (tx *DeclarationTransformer) getNameExpressionPreferringIdentifier(nameExpr
return result
}
}
if ast.IsNoSubstitutionTemplateLiteral(nameExpr) {
// template literals aren't valid module export names
return tx.Factory().NewStringLiteral(nameExpr.Text(), ast.TokenFlagsNone)
}
return nameExpr
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
//// [tests/cases/compiler/declarationEmitCommonjsRequireComputedKey.ts] ////

//// [a.js]
exports.value = 123;
exports.text = "text";
exports.other = true;
exports.nested = { value: 1 };
class Obj {
x = 1;
}
exports.Obj = Obj;

//// [b.js]
const key = "value";
const {[key]: dynamic, ["text"]: text, other, nested: {value}, ...rest} = require("./a"),
sibling = require("./a");
exports.dynamic = dynamic;
exports.text = text;
exports.other = other;
exports.value = value;
exports.rest = rest;
exports.sibling = sibling;

const {[key]: extra, Obj} = require("./a");
/** @param {Obj} o */
function useObj(o) {}
exports.Obj = Obj;
exports.extra = extra;
exports.useObj = useObj;

const {[key]: unusedDynamic, text: unusedText} = require("./a"), keep = 1;
exports.keep = keep;




//// [a.d.ts]
export declare var value: 123;
export declare var text: "text";
export declare var other: true;
export declare var nested: {
value: number;
};
export { Obj };
declare class Obj {
x: number;
}
//// [b.d.ts]
export { dynamic };
export { text };
export { other };
export { value };
export { rest };
export { sibling };
export { Obj };
export { extra };
export { useObj };
export { keep };
import sibling = require("./a");
import { text as text, other } from "./a";
declare const dynamic: any, value: number, rest: any;
import { Obj } from "./a";
declare const extra: any;
/** @param {Obj} o */
declare function useObj(o: Obj): void;
declare const keep = 1;
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
//// [tests/cases/compiler/declarationEmitCommonjsRequireComputedKey.ts] ////

=== b.js ===
const key = "value";
>key : Symbol(key, Decl(b.js, 0, 5))

const {[key]: dynamic, ["text"]: text, other, nested: {value}, ...rest} = require("./a"),
>key : Symbol(key, Decl(b.js, 0, 5))
>dynamic : Symbol(dynamic, Decl(b.js, 1, 7))
>"text" : Symbol(text, Decl(b.js, 1, 22))
>text : Symbol(text, Decl(b.js, 1, 22))
>other : Symbol(other, Decl(b.js, 1, 38))
>nested : Symbol(sibling.nested, Decl(a.js, 2, 21))
>value : Symbol(value, Decl(b.js, 1, 55))
>rest : Symbol(rest, Decl(b.js, 1, 62))
>require : Symbol(require)
>"./a" : Symbol(sibling, Decl(a.js, 0, 0))

sibling = require("./a");
>sibling : Symbol(sibling, Decl(b.js, 1, 89))
>require : Symbol(require)
>"./a" : Symbol(sibling, Decl(a.js, 0, 0))

exports.dynamic = dynamic;
>exports.dynamic : Symbol(dynamic, Decl(b.js, 2, 29))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>dynamic : Symbol(dynamic, Decl(b.js, 2, 29))
>dynamic : Symbol(dynamic, Decl(b.js, 1, 7))

exports.text = text;
>exports.text : Symbol(text, Decl(b.js, 3, 26))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>text : Symbol(text, Decl(b.js, 3, 26))
>text : Symbol(text, Decl(b.js, 1, 22))

exports.other = other;
>exports.other : Symbol(other, Decl(b.js, 4, 20))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>other : Symbol(other, Decl(b.js, 4, 20))
>other : Symbol(other, Decl(b.js, 1, 38))

exports.value = value;
>exports.value : Symbol(value, Decl(b.js, 5, 22))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>value : Symbol(value, Decl(b.js, 5, 22))
>value : Symbol(value, Decl(b.js, 1, 55))

exports.rest = rest;
>exports.rest : Symbol(rest, Decl(b.js, 6, 22))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>rest : Symbol(rest, Decl(b.js, 6, 22))
>rest : Symbol(rest, Decl(b.js, 1, 62))

exports.sibling = sibling;
>exports.sibling : Symbol(sibling, Decl(b.js, 7, 20))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>sibling : Symbol(sibling, Decl(b.js, 7, 20))
>sibling : Symbol(sibling, Decl(b.js, 1, 89))

const {[key]: extra, Obj} = require("./a");
>key : Symbol(key, Decl(b.js, 0, 5))
>extra : Symbol(extra, Decl(b.js, 10, 7))
>Obj : Symbol(Obj, Decl(b.js, 10, 20))
>require : Symbol(require)
>"./a" : Symbol(sibling, Decl(a.js, 0, 0))

/** @param {Obj} o */
function useObj(o) {}
>useObj : Symbol(useObj, Decl(b.js, 10, 43))
>o : Symbol(o, Decl(b.js, 12, 16))

exports.Obj = Obj;
>exports.Obj : Symbol(Obj, Decl(b.js, 12, 21))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>Obj : Symbol(Obj, Decl(b.js, 12, 21))
>Obj : Symbol(Obj, Decl(b.js, 10, 20))

exports.extra = extra;
>exports.extra : Symbol(extra, Decl(b.js, 13, 18))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>extra : Symbol(extra, Decl(b.js, 13, 18))
>extra : Symbol(extra, Decl(b.js, 10, 7))

exports.useObj = useObj;
>exports.useObj : Symbol(useObj, Decl(b.js, 14, 22))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>useObj : Symbol(useObj, Decl(b.js, 14, 22))
>useObj : Symbol(useObj, Decl(b.js, 10, 43))

const {[key]: unusedDynamic, text: unusedText} = require("./a"), keep = 1;
>key : Symbol(key, Decl(b.js, 0, 5))
>unusedDynamic : Symbol(unusedDynamic, Decl(b.js, 17, 7))
>text : Symbol(unusedText, Decl(a.js, 0, 20))
>unusedText : Symbol(unusedText, Decl(b.js, 17, 28))
>require : Symbol(require)
>"./a" : Symbol(sibling, Decl(a.js, 0, 0))
>keep : Symbol(keep, Decl(b.js, 17, 64))

exports.keep = keep;
>exports.keep : Symbol(keep, Decl(b.js, 17, 74))
>exports : Symbol(exports, Decl(b.js, 0, 0))
>keep : Symbol(keep, Decl(b.js, 17, 74))
>keep : Symbol(keep, Decl(b.js, 17, 64))

=== a.js ===
exports.value = 123;
>exports.value : Symbol(value, Decl(a.js, 0, 0))
>exports : Symbol(exports, Decl(a.js, 0, 0))
>value : Symbol(value, Decl(a.js, 0, 0))

exports.text = "text";
>exports.text : Symbol(text, Decl(a.js, 0, 20))
>exports : Symbol(exports, Decl(a.js, 0, 0))
>text : Symbol(text, Decl(a.js, 0, 20))

exports.other = true;
>exports.other : Symbol(other, Decl(a.js, 1, 22))
>exports : Symbol(exports, Decl(a.js, 0, 0))
>other : Symbol(other, Decl(a.js, 1, 22))

exports.nested = { value: 1 };
>exports.nested : Symbol(nested, Decl(a.js, 2, 21))
>exports : Symbol(exports, Decl(a.js, 0, 0))
>nested : Symbol(nested, Decl(a.js, 2, 21))
>value : Symbol(value, Decl(a.js, 3, 18))

class Obj {
>Obj : Symbol(Obj, Decl(a.js, 3, 30))

x = 1;
>x : Symbol(Obj.x, Decl(a.js, 4, 11))
}
exports.Obj = Obj;
>exports.Obj : Symbol(Obj, Decl(a.js, 6, 1))
>exports : Symbol(exports, Decl(a.js, 0, 0))
>Obj : Symbol(Obj, Decl(a.js, 6, 1))
>Obj : Symbol(Obj, Decl(a.js, 3, 30))

Loading
Loading