Unverified Commit 29b39663 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Import Webpack's tests for tree-shaking (#95811)

Imports the tests that Webpack uses for CJS tree-shaking. One test suite
is skipped `deep-reexports`, that's because we don't support that deep
of analysis at the moment and we just bail. WIP because after landing
this stack I will work on improving this.

I did have to make some edits to the tests, a summary is below (courtesy
of Claude):

```
1. Stripped ?query request suffixes (all cases).
Webpack uses require("./x?1") / ?2 to force distinct module instances. Turbopack shares one instance across require sites and aggregates usage, so the queries were removed (require("./x")). The behavioral assertions hold on a shared instance.

2. Distinct copies where per-instance semantics are genuinely required.
A few cases actually depend on separate instances, so we replaced the query with real duplicate files:
- mutate → module-1.js / module-2.js (so mutating one import doesn't leak into the other).
- reexports → add-to-counter-1/2/3.js (the counter must increment 3×).
- reexports-define-property → add-to-counter-1/2.js.

3. Removed __resourceQuery (webpack module-query magic — undefined in turbopack).
In reexports and reexports-define-property: require("./m" + __resourceQuery) → require("./m"), and the dynamic dispatch module reexport.js (require("./" + __resourceQuery.slice(1))) was split into static reexport-direct.js / reexport-indirect.js.

4. Commented out __webpack_exports_info__ / usedExports assertions.
Webpack exposes per-export usage introspection (x.usedExports, __webpack_exports_info__.x.used) that turbopack doesn't populate for CJS. Those specific assertions were commented (the real behavioral checks kept) in: require-member-access, require-member-access-deferred, require-destructuring, this-in-exported-function(-modern), reexport-require-binding, mutate, cjs-to-esm.

5. Case-specific rewrites.
- cjs-to-esm — dropped the require.cache[require.resolve(...)].exports comparison (webpack runtime introspection).
- namespace — changed expect(await import(x)).toBe(require(x)) (object identity) to assert the observable exports (ns.abc, ns.default); turbopack's import() yields an exotic Module namespace, never the same/deep-equal object as require().

6. mjs removed entirely — built on __resourceQuery + per-query instances + .js/.mjs interop divergence; can't even evaluate in turbopack and tests behavior turbopack doesn't share.
```

All tests should be passing.
parent eb7beb59
......@@ -1496,20 +1496,33 @@ impl VisitAstPath for Analyzer<'_, '_> {
n.callee.visit_with_ast_path(self, &mut ast_path);
}
// Guard only the `exports` target arg; the descriptor is visited normally.
// Visit a recognized descriptor as an export value so a top-level `this` taints.
let cjs_export_target_arg = if is_cjs_define_property {
Some(0)
} else {
None
};
self.check_call_expr_for_effects(
&n.callee,
n.args.iter(),
n.span(),
ast_path,
CallOrNewExpr::Call(n),
cjs_export_target_arg,
);
if is_cjs_define_property {
self.with_cjs_export_value(|this| {
this.check_call_expr_for_effects(
&n.callee,
n.args.iter(),
n.span(),
ast_path,
CallOrNewExpr::Call(n),
cjs_export_target_arg,
);
});
} else {
self.check_call_expr_for_effects(
&n.callee,
n.args.iter(),
n.span(),
ast_path,
CallOrNewExpr::Call(n),
cjs_export_target_arg,
);
}
}
fn visit_new_expr<'ast: 'r, 'r>(
......
......@@ -274,6 +274,8 @@ struct TestOptions {
#[serde(default = "default_true")]
scope_hoisting: bool,
#[serde(default)]
cjs_tree_shaking: bool,
#[serde(default)]
minify: bool,
#[serde(default)]
production_chunking: bool,
......@@ -291,6 +293,7 @@ impl Default for TestOptions {
remove_unused_exports: default_true(),
remove_unused_imports: default_true(),
scope_hoisting: default_true(),
cjs_tree_shaking: false,
minify: false,
production_chunking: false,
}
......@@ -443,6 +446,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
import_externals: true,
enable_exports_info_inlining: true,
infer_module_side_effects: true,
cjs_tree_shaking: options.cjs_tree_shaking,
..Default::default()
},
environment: Some(env),
......
export const a = 1
export const b = 2
export const aUsed = __webpack_exports_info__.a.used
export const bUsed = __webpack_exports_info__.b.used
export const x = 1
export const y = 2
export const xUsed = __webpack_exports_info__.x.used
export const yUsed = __webpack_exports_info__.y.used
export const p = 1
export const q = 2
export const pUsed = __webpack_exports_info__.p.used
export const qUsed = __webpack_exports_info__.q.used
export const m = 1
export const n = 2
export const mUsed = __webpack_exports_info__.m.used
export const nUsed = __webpack_exports_info__.n.used
export const x = 1
export const y = 2
export const xUsed = __webpack_exports_info__.x.used
export const yUsed = __webpack_exports_info__.y.used
export const a = 1
export const b = 2
export const c = 3
export const aUsed = __webpack_exports_info__.a.used
export const bUsed = __webpack_exports_info__.b.used
export const cUsed = __webpack_exports_info__.c.used
it('A: should tree-shake through a 4-level CJS star-reexport chain', () => {
const d = require('./a-l4')
expect(d.a).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(d.aUsed).toBe(true)
expect(d.bUsed).toBe(false) // b is never read across the chain
}
})
it('B: should tree-shake a nested namespace reexported through CJS', () => {
const m = require('./b-mid')
expect(m.inner.x).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(m.inner.xUsed).toBe(true)
expect(m.inner.yUsed).toBe(false) // y only reachable via m.inner, never read
}
})
it('C: should tree-shake a sub-namespace star-reexport (ids != [])', () => {
const m = require('./c-mid')
expect(m.p).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(m.pUsed).toBe(true)
expect(m.qUsed).toBe(false)
}
})
it('D: should tree-shake a CJS star-reexport of an ESM `export *` barrel', () => {
const d = require('./d-cjs')
expect(d.m).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(d.mUsed).toBe(true)
expect(d.nUsed).toBe(false)
}
})
it('E: should handle circular CJS star-reexports at runtime', () => {
const one = require('./e-one')
expect(one.second).toBe(2)
})
it('F: should tree-shake a depth-2 nested namespace reexported through CJS', () => {
const m = require('./f-cjs')
expect(m.mid.deep.x).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(m.mid.deep.xUsed).toBe(true)
expect(m.mid.deep.yUsed).toBe(false) // y reachable only via m.mid.deep, never read
}
})
it('G: should tree-shake a diamond of CJS reexports with disjoint usage', () => {
const a = require('./g-p1').a
const b = require('./g-p2').b
expect(a).toBe(1)
expect(b).toBe(2)
if (process.env.NODE_ENV === 'production') {
// each property is pulled through a different reexport path
expect(require('./g-p1').aUsed).toBe(true)
expect(require('./g-p2').bUsed).toBe(true)
expect(require('./g-p1').cUsed).toBe(false) // c used through neither path
}
})
it('J: should tree-shake when ids unwrap a namespace after a star hop', () => {
const m = require('./j-hop2')
expect(m.w).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(m.wUsed).toBe(true)
expect(m.zUsed).toBe(false)
}
})
it('H: should resolve mutually circular CJS star-reexports at runtime', () => {
const a = require('./h-a')
expect(a.onlyB).toBe('B')
expect(a.alsoB).toBe('B2')
expect('onlyA' in a).toBe(false) // overwritten by module.exports = require("./h-b")
})
export const w = 1
export const z = 2
export const wUsed = __webpack_exports_info__.w.used
export const zUsed = __webpack_exports_info__.z.used
module.exports.func = function f() {
'use strict'
return this
}
module.exports.abc = 'abc'
exports.abc = 'abc'
function f(m) {
m.exports = { abc: 'abc', def: 'def' }
}
f(module)
Object.defineProperty(exports, 'abc', { value: 'abc' })
var newObj = {}
exports = newObj
Object.defineProperty(exports, 'def', { value: 'def' })
exports.abc = 'abc'
Object.defineProperties(module, {
exports: {
value: {
abc: 'abc',
def: 'def',
},
},
})
exports.abc = 'abc'
Object.defineProperty(module, 'exports', {
value: {
abc: 'abc',
def: 'def',
},
})
it('should bailout when reading whole exports object from this', () => {
var test = require('./reading-this').test
expect(test().abc).toBe('abc')
})
it('should bailout when reading whole exports object from exports', () => {
var test = require('./reading-exports').test
expect(test().abc).toBe('abc')
})
it('should bailout when reading whole exports object from module.exports', () => {
var test = require('./reading-module-exports').test
expect(test().abc).toBe('abc')
})
it('should reassigning exports (assign values)', () => {
expect(require('./assign-exports-assign').abc).toBe('abc')
expect(require('./assign-exports-assign').def).toBe(undefined)
})
it('should reassigning exports (define values)', () => {
expect(require('./assign-exports-define').abc).toBe('abc')
expect(require('./assign-exports-define').def).toBe(undefined)
})
it('should not mangle or remove nested properties', () => {
expect(require('./nested-property').abc).toBe('abc')
})
it('should be able to access the exports via call context', () => {
expect(require('./accessing-call-context').func().abc).toBe('abc')
var cc = require('./accessing-call-context')
expect(cc.func().abc).toBe('abc')
var func = require('./accessing-call-context').func
expect(func()).toBe(undefined)
})
it('should be able to define an exports property on module (property)', () => {
expect(require('./define-module-property').abc).toBe('abc')
expect(require('./define-module-property').def).toBe('def')
})
it('should be able to define an exports property on module (properties)', () => {
expect(require('./define-module-properties').abc).toBe('abc')
expect(require('./define-module-properties').def).toBe('def')
})
it('should be able to do stuff with the module object', () => {
expect(require('./accessing-module').abc).toBe('abc')
expect(require('./accessing-module').def).toBe('def')
})
it('should be able to use AMD to define exports', () => {
expect(require('./using-amd').abc).toBe('abc')
expect(require('./using-amd').def).toBe('def')
})
var abc = {}
module.exports = abc
module.exports.abc = 'abc'
module.exports.def = 'def'
expect(abc).toEqual({ abc: 'abc', def: 'def' })
it('should allow to require esm', () => {
expect(require('./module').abc).toBe('abc')
expect(typeof require('./module').func).toBe('function')
// Dropped: relies on webpack's `require.cache` / `require.resolve` runtime
// introspection, which turbopack's bundled runtime doesn't populate.
// expect(Object.keys(require("./module").func())).toEqual(
// Object.keys(require.cache[require.resolve("./module?2")].exports)
// );
})
export const abc = 'abc'
export const def = 'def'
export const func = function () {
'use strict'
return this
}
import def, { named, __esModule } from './module'
import * as ns from './module'
it('should allow to import module with getters', () => {
expect(def).toBe('default')
expect(named).toBe('named')
expect(__esModule).toBe(true)
expect(ns.default).toBe('default')
expect(ns.named).toBe('named')
expect(ns.__esModule).toBe(true)
const indirect = Object(ns)
expect(indirect.default).toBe('default')
expect(indirect.named).toBe('named')
expect(indirect.__esModule).toBe(true)
})
Object.defineProperty(exports, '__esModule', { get: () => true })
Object.defineProperty(exports, 'default', { get: () => 'default' })
Object.defineProperty(exports, 'named', { get: () => 'named' })
import m1 from './module'
import m2 from './module'
import { abc } from './module'
it('should allow to import cjs with esm', () => {
expect(m1.abc).toBe('abc')
expect(m2).toEqual({ abc: 'abc', def: 'def' })
expect(abc).toBe('abc')
})
Object.defineProperty(exports, 'abc', { enumerable: true, value: 'abc' })
Object.defineProperty(exports, 'def', { enumerable: true, value: 'def' })
Object.defineProperty(module.exports, 'abc', {
enumerable: true,
value: 'abc',
})
Object.defineProperty(module.exports, 'def', {
enumerable: true,
value: 'def',
})
Object.defineProperty(this, 'abc', { enumerable: true, value: 'abc' })
Object.defineProperty(this, 'def', { enumerable: true, value: 'def' })
class Test {
getString() {
return 'hello'
}
}
const getExports = () => ({ __esModule: true, default: Test })
module.exports = getExports()
class Test {
getString() {
return 'hello'
}
}
const getExports = () => ({ default: Test })
module.exports = getExports()
Object.defineProperty(exports, '__esModule', { value: true })
class Test {
getString() {
return 'hello'
}
}
exports.default = Test
it('should allow to export via exports', () => {
expect(require('./assign-exports-property').abc).toBe('abc')
expect(require('./assign-exports-property')).toEqual({
abc: 'abc',
def: 'def',
})
})
it('should allow to export via module.exports', () => {
expect(require('./assign-module-exports-property').abc).toBe('abc')
expect(require('./assign-module-exports-property')).toEqual({
abc: 'abc',
def: 'def',
})
})
it('should allow to export via this', () => {
expect(require('./assign-this-property').abc).toBe('abc')
expect(require('./assign-this-property')).toEqual({
abc: 'abc',
def: 'def',
})
})
it('should allow to export via define property on exports', () => {
expect(require('./define-exports-property').abc).toBe('abc')
expect(require('./define-exports-property')).toEqual({
abc: 'abc',
def: 'def',
})
})
it('should allow to export via define property on module.exports', () => {
expect(require('./define-module-exports-property').abc).toBe('abc')
expect(require('./define-module-exports-property')).toEqual({
abc: 'abc',
def: 'def',
})
})
it('should allow to export via define property on this', () => {
expect(require('./define-this-property').abc).toBe('abc')
expect(require('./define-this-property')).toEqual({
abc: 'abc',
def: 'def',
})
})
it('should allow to read own exports via exports', () => {
var test = require('./reading-self-from-exports').test
expect(test()).toBe('abc')
})
it('should allow to read own exports via module.exports', () => {
var test = require('./reading-self-from-module-exports').test
expect(test()).toBe('abc')
})
it('should allow to read own exports via this', () => {
var test = require('./reading-self-from-this').test
expect(test()).toBe('abc')
})
it('should allow to attach exports to object', () => {
expect(require('./attach-to-object').abc).toBe('abc')
expect(require('./attach-to-object').def).toBe('def')
expect(require('./attach-to-object').abc).toBe('abc')
expect(require('./attach-to-object').def).toBe('def')
})
it('should allow to attach exports to function', () => {
expect(require('./attach-to-function')()).toBe('abc')
expect(require('./attach-to-function').def).toBe('def')
expect(require('./attach-to-function')()).toBe('abc')
expect(require('./attach-to-function').def).toBe('def')
})
it('should allow to attach exports to arrow function', () => {
expect(require('./attach-to-arrow-function')()).toBe('abc')
expect(require('./attach-to-arrow-function').def).toBe('def')
expect(require('./attach-to-arrow-function')()).toBe('abc')
expect(require('./attach-to-arrow-function').def).toBe('def')
})
it('should properly handle export / require `default`', () => {
expect(require('./require-default').moduleExportsDefault).toBe('hello')
expect(require('./require-default').hello1).toBe('hello')
expect(require('./require-default').hello2).toBe('hello')
expect(require('./require-default').hello3).toBe('hello')
expect(require('./require-default').hello4).toBe('hello')
expect(require('./require-default').hello5).toBe('hello')
expect(require('./require-default').hello6).toBe('hello')
expect(require('./require-default').hello7).toBe('hello')
expect(require('./require-default').hello8).toBe('hello')
})
const ModuleExportsDefaultTest = require('./module-exports-default').default
const Test1 = require('./exports-default').default
import Test2 from './exports-default'
const Test3 = require('./exports-default-flagged').default
import Test4 from './exports-default-flagged'
const Test5 = require('./exports-default-bailout').default
import Test6 from './exports-default-bailout'
const Test7 = require('./exports-default-bailout-flagged').default
import Test8 from './exports-default-bailout-flagged'
const moduleExportsDefaultTest = new ModuleExportsDefaultTest()
const test1 = new Test1()
const test2 = new Test2.default()
const test3 = new Test3()
const test4 = new Test4()
const test5 = new Test5()
const test6 = new Test6.default()
const test7 = new Test7()
const test8 = new Test8()
export const moduleExportsDefault = moduleExportsDefaultTest.getString()
export const hello1 = test1.getString()
export const hello2 = test2.getString()
export const hello3 = test3.getString()
export const hello4 = test4.getString()
export const hello5 = test5.getString()
export const hello6 = test6.getString()
export const hello7 = test7.getString()
export const hello8 = test8.getString()
it('should be able to import a module via require and property', () => {
expect(require('./module').abc).toBe('abc')
})
it('should be able to import a module via require and destruct', () => {
var { abc } = require('./module')
expect(abc).toBe('abc')
})
it('should be able to import a module via require and exports object', () => {
var module1 = require('./module')
expect(module1.abc).toBe('abc')
var module2 = require('./module')
expect(module2).toEqual({ abc: 'abc', def: 'def' })
})
import module1 from './module-1'
// Dropped the `{ a }` named import: turbopack resolves a named CJS import that
// isn't a static export to `undefined` rather than a live getter, so a
// runtime-added `exports.a` isn't observed through the binding.
import module2 from './module-2'
it('should allow mutating imported modules (changing existing exports)', () => {
expect(module1.abc).toBe('abc')
expect(module1.def).toBe('def')
module1.abc = 'new-abc'
expect(module1.abc).toBe('new-abc')
expect(module1.def).toBe('def')
})
it('should allow mutating imported modules (adding new properties)', () => {
expect(module2.abc).toBe('abc')
expect(module2.def).toBe('def')
expect(module2.ghi).toBe(undefined)
expect(module2.Oi).toBe(undefined)
expect(module2.a).toBe(undefined)
// expect(a).toBe(undefined);
expect(module2['']).toBe(undefined)
module2.ghi = 'ghi'
module2.Oi = 'Oi'
module2.a = 'a'
module2[''] = {}
module2[''].abc = 'abc'
expect(module2.abc).toBe('abc')
expect(module2.def).toBe('def')
expect(module2.ghi).toBe('ghi')
expect(module2.Oi).toBe('Oi')
expect(module2.a).toBe('a')
// expect(a).toBe("a");
expect(module2['']).toEqual({ abc: 'abc' })
expect(module2[''].abc).toBe('abc')
})
// Rewritten to assert the observable `__esModule` interop exports rather than
// object identity between `import()` and `require()`: turbopack's `import()`
// yields an exotic Module namespace object, never the same (or deep-equal) plain
// object that `require()` returns.
it('should allow to create namespace exports via __esModule on exports', async () => {
const ns = await import('./namespace-via-exports')
expect(ns.abc).toBe('abc')
expect(ns.default).toBe('default')
})
it('should allow to create namespace exports via __esModule on literal', async () => {
const ns = await import('./namespace-via-literal')
expect(ns.abc).toBe('abc')
expect(ns.default).toBe('default')
})
it('should allow to create namespace exports via __esModule with Object.defineProperty', async () => {
const ns = await import('./namespace-via-define-property')
expect(ns.abc).toBe('abc')
expect(ns.default).toBe('default')
})
it('should allow to create namespace exports via __esModule with Object.defineProperty minimized true', async () => {
const ns = await import('./namespace-via-define-property-minimized')
expect(ns.abc).toBe('abc')
expect(ns.default).toBe('default')
})
it('should allow to create namespace exports via __esModule with Object.defineProperties', async () => {
const ns = await import('./namespace-via-define-properties')
expect(ns.abc).toBe('abc')
expect(ns.default).toBe('default')
})
Object.defineProperties(exports, {
__esModule: { value: true },
abc: { enumerable: true, value: 'abc' },
default: { enumerable: true, value: 'default' },
})
Object.defineProperty(exports, '__esModule', { value: !0 })
exports.abc = 'abc'
exports.default = 'default'
Object.defineProperty(exports, '__esModule', { value: true })
exports.abc = 'abc'
exports.default = 'default'
it('should not rewrite this nested in functions', () => {
const f = require('./module').fff
expect(f.test1).toBe(true)
expect(f.test2).toBe(true)
})
function F() {
this.test1 = true
Object.defineProperty(this, 'test2', { value: true })
}
exports.fff = new F()
it('should replace Object.defineProperty correctly with brackets', () => {
expect(require('./module').test).toBe(true)
})
it('should be able to export an object literal', () => {
expect(require('./direct-object').abc).toBe('abc')
expect(require('./direct-object')).toEqual({ abc: 'abc', def: 'def' })
})
it('should be able to export an object literal indirect', () => {
expect(require('./indirect-object').abc).toBe('abc')
expect(require('./indirect-object')).toEqual({ abc: 'abc', def: 'def' })
})
it('should parse nested requires successfully', () => {
expect(require('./nested-require').value).toBe(42)
})
import { ns as whole } from './reexport-whole'
import { ns as viaSpecifier } from './reexport-specifier'
import { picked, flag } from './partial'
it('should keep the whole exports object when an `export const` require binding is re-exported (#21135)', () => {
expect(whole.a).toBe('a')
expect(whole.b).toBe('b')
// Re-exporting the binding lets the value escape, so nothing may be shaken.
// expect(whole.usedExports).toBe(true);
})
it('should keep the whole exports object when a require binding is re-exported via a specifier (#21135)', () => {
expect(viaSpecifier.a).toBe('a')
expect(viaSpecifier.b).toBe('b')
// expect(viaSpecifier.usedExports).toBe(true);
})
it('should still tree-shake when only specific members of a require binding are re-exported', () => {
expect(picked).toBe('a')
// `b` is never touched, so it is shaken out of the required module.
// expect(flag).toEqual(["a", "usedExports"]);
})
exports.a = 'a'
exports.b = 'b'
// exports.usedExports = __webpack_exports_info__.usedExports;
const ns = require('./module')
export const picked = ns.a
// export const flag = ns.usedExports;
import { data as fromConst } from './reexport-const'
import { data as fromSpecifier } from './reexport-specifier'
import { data as fromImport } from './reexport-import'
const expected = { a: 1, b: 2, nested: { x: 3 } }
it('should keep the whole JSON when `export const data = require(json)` (#21135)', () => {
expect(fromConst).toEqual(expected)
})
it('should keep the whole JSON when a required JSON binding is re-exported (#21135)', () => {
expect(fromSpecifier).toEqual(expected)
})
it('should keep the whole JSON when an imported JSON default is re-exported', () => {
expect(fromImport).toEqual(expected)
})
it('should reexport a whole module via Object.defineProperty value (exports, module.exports, this)', () => {
expect(require('./reexport-whole-define').module1.abc).toBe('abc')
expect(require('./reexport-whole-define').module2.abc).toBe('abc')
expect(require('./reexport-whole-define').module3.abc).toBe('abc')
})
it('should reexport an imported property via Object.defineProperty value (exports, module.exports, this)', () => {
expect(require('./reexport-property-define').property1).toBe('abc')
expect(require('./reexport-property-define').property2).toBe('abc')
expect(require('./reexport-property-define').property3).toBe('abc')
})
it('should reexport a reexported module via Object.defineProperty value', () => {
expect(require('./reexport-reexport-define').reexport1.abc).toBe('abc')
expect(require('./reexport-reexport-define').reexport2.abc).toBe('abc')
expect(require('./reexport-reexport-define').reexport3.abc).toBe('abc')
})
it('should reexport a deeply nested property via Object.defineProperty value', () => {
expect(require('./reexport-nested').nested).toBe('nested-value')
})
it('should reexport via a lazy Object.defineProperty getter (arrow, function, method)', () => {
expect(require('./reexport-getter-define').getter1.abc).toBe('abc')
expect(require('./reexport-getter-define').getter2).toBe('abc')
expect(require('./reexport-getter-define').getter3.abc).toBe('abc')
})
it('should keep executing eager (value) reexported modules even when unused', () => {
const counter = require('./counter')
counter.value = 0
Object.defineProperty(exports, 'unused1', {
value: require('./add-to-counter-1'),
})
Object.defineProperty(exports, 'unused2', {
value: require('./add-to-counter-2').abc,
})
expect(counter.value).toBe(2)
})
it('should not execute a reexported module until the getter is accessed', () => {
const counter = require('./counter')
counter.value = 0
const m = require('./reexport-lazy-getter')
// the require ran, but the lazy getter has not been accessed yet
expect(counter.value).toBe(0)
// accessing the getter triggers the underlying require
expect(m.lazy.abc).toBe(42)
expect(counter.value).toBe(1)
})
it('should preserve the setter when a get/set descriptor wraps a reexport', () => {
const m = require('./reexport-getter-setter')
expect(m.value).toBe('abc') // getter returns the reexported value
m.value = 'written' // setter must still exist (would throw if dropped)
expect(m.getLastSet()).toBe('written')
expect(m.value).toBe('abc') // getter is unaffected by the write
})
it('should never execute a module behind an unused getter reexport', () => {
const counter = require('./counter')
counter.value = 0
require('./reexport-unused-getter')
expect(counter.value).toBe(0)
})
// Arrow getter, whole module.
Object.defineProperty(exports, 'getter1', {
enumerable: true,
get: () => require('./module'),
})
// Function-expression getter, property access.
Object.defineProperty(module.exports, 'getter2', {
enumerable: true,
get: function () {
return require('./module').abc
},
})
// Method-shorthand getter on `this`.
Object.defineProperty(this, 'getter3', {
enumerable: true,
get() {
return require('./module')
},
})
let lastSet
// A get/set descriptor: the getter re-exports a required value, but the setter
// must be preserved (it cannot be reproduced by the reexport rewrite).
Object.defineProperty(exports, 'value', {
get: () => require('./module').abc,
set: (v) => {
lastSet = v
},
})
exports.getLastSet = () => lastSet
Object.defineProperty(exports, 'lazy', {
enumerable: true,
get: () => require('./lazy-counter'),
})
Object.defineProperty(exports, 'nested', {
value: require('./nested').outer.inner,
})
Object.defineProperty(exports, 'property1', {
value: require('./module').abc,
})
Object.defineProperty(module.exports, 'property2', {
value: require('./module').abc,
})
Object.defineProperty(this, 'property3', {
value: require('./module').abc,
})
Object.defineProperty(exports, 'reexport1', {
value: require('./reexport-whole-define').module1,
})
Object.defineProperty(module.exports, 'reexport2', {
value: require('./reexport-whole-define').module2,
})
Object.defineProperty(this, 'reexport3', {
value: require('./reexport-whole-define').module3,
})
Object.defineProperty(exports, 'neverUsed', {
enumerable: true,
get: () => require('./lazy-counter'),
})
Object.defineProperty(exports, 'module1', {
value: require('./module'),
})
Object.defineProperty(module.exports, 'module2', {
value: require('./module'),
})
Object.defineProperty(this, 'module3', {
value: require('./module'),
})
it('should allow to reexport a exports object (this, exports)', () => {
expect(require('./reexport-whole-exports').module1.abc).toBe('abc')
expect(require('./reexport-whole-exports').module2.abc).toBe('abc')
expect(require('./reexport-whole-exports').module3.abc).toBe('abc')
expect(require('./reexport-whole-exports').module4.abc).toBe('abc')
})
it('should allow to reexport a exports object (module.exports, object literal)', () => {
expect(require('./reexport-whole-module-exports').module1.abc).toBe('abc')
expect(require('./reexport-whole-module-exports').module2.abc).toBe('abc')
expect(require('./reexport-whole-module-exports').module3.abc).toBe('abc')
expect(require('./reexport-whole-module-exports').module4.abc).toBe('abc')
})
it('should allow to reexport a imported property (this, exports)', () => {
expect(require('./reexport-property-exports').property1).toBe('abc')
expect(require('./reexport-property-exports').property2).toBe('abc')
expect(require('./reexport-property-exports').property3).toBe('abc')
expect(require('./reexport-property-exports').property4).toBe('abc')
})
it('should allow to reexport a imported property (module.exports, object literal)', () => {
expect(require('./reexport-property-module-exports').property1).toBe('abc')
expect(require('./reexport-property-module-exports').property2).toBe('abc')
expect(require('./reexport-property-module-exports').property3).toBe('abc')
expect(require('./reexport-property-module-exports').property4).toBe('abc')
})
it('should allow to reexport a reexported exports object (this, exports)', () => {
expect(require('./reexport-reexport-exports').reexport1.abc).toBe('abc')
expect(require('./reexport-reexport-exports').reexport2.abc).toBe('abc')
expect(require('./reexport-reexport-exports').reexport3.abc).toBe('abc')
expect(require('./reexport-reexport-exports').reexport4.abc).toBe('abc')
})
it('should allow to reexport a reexported exports object (module.exports, object literal)', () => {
expect(require('./reexport-reexport-module-exports').reexport1.abc).toBe(
'abc'
)
expect(require('./reexport-reexport-module-exports').reexport2.abc).toBe(
'abc'
)
expect(require('./reexport-reexport-module-exports').reexport3.abc).toBe(
'abc'
)
expect(require('./reexport-reexport-module-exports').reexport4.abc).toBe(
'abc'
)
})
it('should keep executing modules even when unused', () => {
const counter = require('./counter')
counter.value = 0
exports.unused1 = require('./add-to-counter-1')
exports.unused2 = require('./add-to-counter-2').abc
expect((exports.unused3 = require('./add-to-counter-3').abc)).toBe(42)
expect(counter.value).toBe(3)
})
it('should allow to reexport a reexported module that bails out (indirect)', () => {
const abc = require('./reexport-indirect').module1.abc
const bailout = Object(require('./module'))
expect(abc).toBe(bailout.abc)
})
it('should allow to reexport a reexported module that bails out (direct)', () => {
const abc = require('./reexport-direct').abc
const bailout = Object(require('./module'))
expect(abc).toBe(bailout.abc)
})
exports.property1 = require('./module').abc
var m2 = require('./module')
exports.property2 = m2.abc
this.property3 = require('./module').abc
var m4 = require('./module')
this.property4 = m4.abc
var m2 = require('./module')
module.exports = {
property1: require('./module').abc,
property2: m2.abc,
}
module.exports.property3 = require('./module').abc
var m4 = require('./module')
module.exports.property4 = m4.abc
exports.reexport1 = require('./reexport-whole-exports').module1
var m2 = require('./reexport-whole-exports')
exports.reexport2 = m2.module2
this.reexport3 = require('./reexport-whole-exports').module3
var m4 = require('./reexport-whole-exports')
this.reexport4 = m4.module4
var m2 = require('./reexport-whole-module-exports')
module.exports = {
reexport1: require('./reexport-whole-module-exports').module1,
reexport2: m2.module2,
}
module.exports.reexport3 = require('./reexport-whole-module-exports').module3
var m4 = require('./reexport-whole-module-exports')
module.exports.reexport4 = m4.module4
exports.module1 = require('./module')
var m2 = require('./module')
exports.module2 = m2
this.module3 = require('./module')
var m4 = require('./module')
this.module4 = m4
var module2 = require('./module')
module.exports = {
module1: require('./module'),
module2,
}
module.exports.module3 = require('./module')
var m4 = require('./module')
module.exports.module4 = m4
export const a = 'a/a'
export const b = 'a/b'
// export const usedExports = __webpack_exports_info__.usedExports;
export const a = 'b/a'
export const b = 'b/b'
// export const usedExports = __webpack_exports_info__.usedExports;
it('should static analyze require destructuring assignment', () => {
const { a } = require('./module')
expect(a).toBe('a')
// expect(usedExports).toEqual(["a", "usedExports"]);
})
it('should support require context destructuring assignment', () => {
const file = 'a'
const { a } = require(`./dir/${file}.js`)
expect(a).toBe('a/a')
// expect(usedExports).toEqual(["a", "usedExports"]);
})
it('should static analyze aliased require destructuring', () => {
const { a: renamedA } = require('./module')
expect(renamedA).toBe('a')
// expect(usedExports).toEqual(["a", "usedExports"]);
})
it('should support require context aliased destructuring assignment', () => {
const file = 'a'
const { a: renamedA } = require(`./dir/${file}.js`)
expect(renamedA).toBe('a/a')
// expect(usedExports).toEqual(["a", "usedExports"]);
})
it('should static analyze require destructuring with default values', () => {
const { a = 'fallback' } = require('./module')
expect(a).toBe('a')
// expect(usedExports).toEqual(["a", "usedExports"]);
})
it('should bail on rest element in require destructuring', () => {
const { ...rest } = require('./module-rest')
// expect(usedExports).toBe(true);
expect(rest).toEqual({ a: 'a', b: 'b' })
})
exports.a = 'a'
exports.b = 'b'
// exports.usedExports = __webpack_exports_info__.usedExports;
exports.a = 'a'
exports.b = 'b'
// exports.usedExports = __webpack_exports_info__.usedExports;
// Simulates whatwg-url/lib/URL-impl.js
exports.implementation = class URLImpl {
constructor(args) {
this.href = args[0]
}
}
exports.unused = 'should be tree-shaken'
// exports.usedExports = __webpack_exports_info__.usedExports;
it('should not tree-shake exports accessed via a deferred require binding', () => {
const { interface: URL } = require('./wrapper')
const u = new URL('https://example.com/')
expect(u._impl).toBeTruthy()
expect(u._impl.href).toBe('https://example.com/')
})
it('should still tree-shake unused exports from the deferred module', () => {
const Impl = require('./impl')
// "implementation" is used (via wrapper.js), "unused" is not
// expect(Impl.usedExports).toEqual(["implementation", "usedExports"]);
})
// Simulates whatwg-url/lib/URL.js pattern: function bodies reference
// `Impl` which is declared at the bottom (deferred require for circular deps).
exports.setup = (obj, constructorArgs) => {
obj._impl = new Impl.implementation(constructorArgs)
return obj
}
class URL {
constructor(url) {
return exports.setup(Object.create(URL.prototype), [url])
}
}
exports.interface = URL
// Deferred require at the bottom of the file (handles circular dependencies)
const Impl = require('./impl')
it('should tree-shake CommonJS exports when accessed via a member call', () => {
const m = require('./module')
expect(m.a()).toBe('a')
// expect(m.usedExports).toEqual(["a", "usedExports"]);
})
it('should tree-shake CommonJS exports when accessed as a property', () => {
const m = require('./module')
const a = m.a
// const u = m.usedExports;
expect(a()).toBe('a')
// expect(u).toEqual(["a", "usedExports"]);
})
it('should tree-shake CommonJS exports when accessed with a string literal', () => {
const m = require('./module')
expect(m['a']()).toBe('a')
// expect(m.usedExports).toEqual(["a", "usedExports"]);
})
it('should bail out when the require result is read as a value (spread)', () => {
const m = require('./module-rest')
// Spreading the namespace forces every export to remain reachable.
const all = { ...m }
expect(all.a).toBe('a')
expect(all.b).toBe('b')
// expect(all.usedExports).toBe(true);
})
it('should bail out when the require result is accessed with a dynamic key', () => {
const m = require('./module-rest')
const key = 'a'
expect(m[key]).toBe('a')
// Dynamic-key access cannot be statically tracked, so every export must
// remain reachable.
// expect(m.usedExports).toBe(true);
})
it('should bail out when the require result is called directly', () => {
const m = require('./module-call')
expect(m()).toBe('direct-call')
// Calling the namespace itself means the whole exports object is observable;
// every attached property must still be reachable.
expect(m.x).toBe('x')
// `module.exports = fn` already prevents named-export tracking, so usage
// reports `null` ("no specific usage tracked").
// expect(m.usedExports).toBe(null);
})
const fn = function () {
return 'direct-call'
}
fn.x = 'x'
// fn.usedExports = __webpack_exports_info__.usedExports;
module.exports = fn
exports.a = 'a'
exports.b = 'b'
// exports.usedExports = __webpack_exports_info__.usedExports;
exports.a = function a() {
return 'a'
}
exports.b = 'b'
// exports.usedExports = __webpack_exports_info__.usedExports;
it('should still tree-shake when this appears in static blocks and class fields', () => {
const m = require('./module-inner')
expect(m.a()).toBe(2)
// expect(m.usedExports).toEqual(["a", "usedExports"]);
})
exports.a = function () {
// `this` in static blocks and class field values is not the exports object,
// so it must not disable tree-shaking
const results = []
class Inner {
static {
results.push(this)
}
[`computed${1}`] = 1
field = this
method() {
results.push(this)
}
}
new Inner().method()
return results.length
}
exports.b = function () {
return 'b'
}
// exports.usedExports = __webpack_exports_info__.usedExports;
import * as m from './module-esm-used'
// Calling a namespace method passes the exports object as `this`
export const result = m.sign('/esm')
it('should keep all exports when an exported function uses this (#21178)', () => {
const signUtils = require('./module')
expect(signUtils.buildCanonicalString('/bucket')).toBe('resource:/bucket')
// `this` may reach any export, so nothing may be shaken.
// expect(signUtils.usedExports).toBe(true);
})
it('should keep all exports when a module.exports member function uses this', () => {
const m = require('./module-module-exports')
expect(m.a()).toBe('b')
// expect(m.usedExports).toBe(true);
})
it('should keep all exports when a top-level this member function uses this', () => {
const m = require('./module-top-this')
expect(m.a()).toBe('b')
// expect(m.usedExports).toBe(true);
})
it('should keep all exports when this is captured by a nested arrow function', () => {
const m = require('./module-arrow')
expect(m.a()).toBe('b')
// expect(m.usedExports).toBe(true);
})
it('should keep all exports when a defineProperty export descriptor uses this', () => {
const m = require('./module-define')
expect(m.a()).toBe('b')
expect(m.c).toBe('b')
m.d = '!'
expect(m.received).toBe('b!')
// expect(m.usedExports).toBe(true);
})
it('should detect this in generator, async, default-param and computed accesses', async () => {
const m = require('./module-misc')
expect(m.viaGenerator().next().value).toBe('h')
expect(await m.viaAsync()).toBe('h')
expect(m.viaDefaultParam()).toBe('h')
expect(m.viaComputed()).toBe('h')
// expect(m.usedExports).toBe(true);
})
it('should keep all exports when the consumer is an ESM module', () => {
const { result } = require('./esm')
expect(result).toBe('resource:/esm')
})
it('should still tree-shake when this only appears in nested functions', () => {
const m = require('./module-inner')
expect(m.a()).toBe(2)
// expect(m.usedExports).toEqual(["a", "usedExports"]);
})
it('should still tree-shake when this is used in an exported class', () => {
const m = require('./module-class')
expect(new m.Impl().x).toBe('x')
// expect(m.usedExports).toEqual(["Impl", "usedExports"]);
})
it('should still tree-shake when the exported values contain no this', () => {
const m = require('./module-no-this')
expect(m.a()).toBe('function')
// expect(m.usedExports).toEqual(["a", "usedExports"]);
})
exports.a = function () {
// Arrows inherit the enclosing function's `this`
return (() => this.b())()
}
exports.b = function () {
return 'b'
}
// exports.usedExports = __webpack_exports_info__.usedExports;
exports.Impl = class Impl {
constructor() {
// `this` in an exported class is the instance, never the exports object
this.x = 'x'
}
}
exports.b = function () {
return 'b'
}
// exports.usedExports = __webpack_exports_info__.usedExports;
Object.defineProperty(exports, 'a', {
value: function a() {
return this.b()
},
})
Object.defineProperty(exports, 'b', {
value: function b() {
return 'b'
},
})
Object.defineProperty(exports, 'c', {
get() {
// getters are called with the exports object as `this` too
return this.b()
},
})
const enumerable = { enumerable: true }
Object.defineProperty(exports, 'd', {
...enumerable,
set(value) {
// setters are called with the exports object as `this` too
this.received = this.b() + value
},
})
// exports.usedExports = __webpack_exports_info__.usedExports;
exports.build = function (resourcePath) {
return `resource:${resourcePath}`
}
exports.sign = function (resourcePath) {
return this.build(resourcePath)
}
exports.a = function () {
// `this` in nested functions and class bodies is not the exports object,
// so it must not disable tree-shaking
const results = []
function inner() {
results.push(this)
}
class Inner {
method() {
results.push(this)
}
}
inner.call('inner')
new Inner().method()
return results.length
}
exports.b = function () {
return 'b'
}
// exports.usedExports = __webpack_exports_info__.usedExports;
exports.helper = function () {
return 'h'
}
exports.viaGenerator = function* () {
yield this.helper()
}
exports.viaAsync = async function () {
return this.helper()
}
exports.viaDefaultParam = function (x = this.helper()) {
return x
}
exports.viaComputed = function () {
return this['helper']()
}
// exports.usedExports = __webpack_exports_info__.usedExports;
module.exports.a = function () {
return this.b()
}
module.exports.b = function () {
return 'b'
}
// module.exports.usedExports = __webpack_exports_info__.usedExports;
function helper() {
// `this` outside an exported value does not disable tree-shaking
return this
}
exports.a = function () {
return typeof helper
}
exports.b = function () {
return 'b'
}
// exports.usedExports = __webpack_exports_info__.usedExports;
this.a = function () {
return this.b()
}
this.b = function () {
return 'b'
}
// this.usedExports = __webpack_exports_info__.usedExports;
exports.buildCanonicalizedResource = function (resourcePath) {
return `resource:${resourcePath}`
}
exports.buildCanonicalString = function (resourcePath) {
// `this` is the exports object when called as `signUtils.buildCanonicalString()`
return this.buildCanonicalizedResource(resourcePath)
}
// exports.usedExports = __webpack_exports_info__.usedExports;
var xxx = _interopRequireDefault(require('./module'))
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj }
}
module.exports = xxx.default.abc
it('should support typescript export *', () => {
expect(require('./typescript-reexport').abc).toBe('abc')
})
it('should support babel default interop', () => {
var xxx2 = _interopRequireDefault(require('./module'))
var xxx3 = _interopRequireDefault(require('./module'))
expect(xxx2.default.abc).toBe('abc')
expect(xxx3.default).toEqual({ abc: 'abc', def: 'def' })
})
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj }
}
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]
}
__export(require('./module'))
import m from './module'
it('should allow any name as exports in CommonJs', () => {
expect(m.abc).toBe('abc')
expect(m['']).toBe('')
expect(m['default']).toBe('default')
expect(m['0']).toBe('0')
expect(m[1]).toBe(1)
expect(m.length).toBe('length')
expect(m['0_0']).toBe('0_0')
expect(m.if).toBe('if')
expect(m['\0']).toBe('\0')
expect(m['\n']).toBe('\n')
expect(m['*/']).toBe('*/')
expect(m['a.b.c']).toBe('a.b.c')
})
exports.abc = 'abc'
exports[''] = ''
exports['default'] = 'default'
exports['0'] = '0'
exports[1] = 1
exports.length = 'length'
exports['0_0'] = '0_0'
exports.if = 'if'
exports['\0'] = '\0'
exports['\n'] = '\n'
exports['*/'] = '*/'
exports['a.b.c'] = 'a.b.c'
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment