Skip to content

Commit d35cdd9

Browse files
committed
feat: optimize out some code in bundles
1 parent aabf4de commit d35cdd9

3 files changed

Lines changed: 128 additions & 106 deletions

File tree

src/dark.cjs

Lines changed: 50 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -52,57 +52,63 @@ function createCallerLocationHook() {
5252
return { installLocationInNextTest, getCallerLocation }
5353
}
5454

55-
// Easy on Node.js >= 22.3.0 || ^20.16.0, but we polyfill for the rest
56-
function getTestNamePath(t) {
57-
// No implementation in Node.js yet, will have to PR
58-
if (t.fullName) return t.fullName.split(' > ')
59-
60-
if (process.env.EXODUS_TEST_ENGINE === 'node:test') {
61-
// We are on Node.js < 22.3.0 where even t.fullName doesn't exist yet, polyfill
62-
const namePath = Symbol('namePath')
63-
const getNamePath = Symbol('getNamePath')
64-
try {
65-
if (t[namePath]) return t[namePath]
66-
67-
// Sigh, ok, whatever
68-
const { Test } = require('node:internal/test_runner/test')
55+
// Optimized out in 'bundle' env
56+
function getTestNamePathFromNode(t) {
57+
// We are on Node.js < 22.3.0 where even t.fullName doesn't exist yet, polyfill
58+
const namePath = Symbol('namePath')
59+
const getNamePath = Symbol('getNamePath')
60+
try {
61+
if (t[namePath]) return t[namePath]
62+
63+
// Sigh, ok, whatever
64+
const { Test } = require('node:internal/test_runner/test')
65+
66+
const usePathName = Symbol('usePathName')
67+
const restoreName = Symbol('restoreName')
68+
Test.prototype[getNamePath] = function () {
69+
if (this === this.root) return []
70+
return [...(this.parent?.[getNamePath]() || []), this.name]
71+
}
6972

70-
const usePathName = Symbol('usePathName')
71-
const restoreName = Symbol('restoreName')
72-
Test.prototype[getNamePath] = function () {
73-
if (this === this.root) return []
74-
return [...(this.parent?.[getNamePath]() || []), this.name]
73+
const diagnostic = Test.prototype.diagnostic
74+
Test.prototype.diagnostic = function (...args) {
75+
if (args[0] === usePathName) {
76+
this[restoreName] = this.name
77+
this.name = this[getNamePath]()
78+
return
7579
}
7680

77-
const diagnostic = Test.prototype.diagnostic
78-
Test.prototype.diagnostic = function (...args) {
79-
if (args[0] === usePathName) {
80-
this[restoreName] = this.name
81-
this.name = this[getNamePath]()
82-
return
83-
}
81+
if (args[0] === restoreName) {
82+
this.name = this[restoreName]
83+
delete this[restoreName]
84+
return
85+
}
8486

85-
if (args[0] === restoreName) {
86-
this.name = this[restoreName]
87-
delete this[restoreName]
88-
return
89-
}
87+
return diagnostic.apply(this, args)
88+
}
9089

91-
return diagnostic.apply(this, args)
92-
}
90+
const TestContextProto = Object.getPrototypeOf(t)
91+
Object.defineProperty(TestContextProto, namePath, {
92+
get() {
93+
this.diagnostic(usePathName)
94+
const result = this.name
95+
this.diagnostic(restoreName)
96+
return result
97+
},
98+
})
99+
100+
return t[namePath]
101+
} catch {}
102+
}
93103

94-
const TestContextProto = Object.getPrototypeOf(t)
95-
Object.defineProperty(TestContextProto, namePath, {
96-
get() {
97-
this.diagnostic(usePathName)
98-
const result = this.name
99-
this.diagnostic(restoreName)
100-
return result
101-
},
102-
})
104+
// Easy on Node.js >= 22.3.0 || ^20.16.0, but we polyfill for the rest
105+
function getTestNamePath(t) {
106+
// No implementation in Node.js yet, will have to PR
107+
if (t.fullName) return t.fullName.split(' > ')
103108

104-
return t[namePath]
105-
} catch {}
109+
if (process.env.EXODUS_TEST_ENGINE === 'node:test') {
110+
const names = getTestNamePathFromNode(t)
111+
if (names) return names
106112
}
107113

108114
return [t.name] // last resort

src/jest.config.js

Lines changed: 73 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { specialEnvironments } from './jest.environment.js'
44

55
const skipPreset = new Set(['ts-jest'])
66
const EXTS = `.?([cm])[jt]s?(x)` // we differ from jest, allowing [cm] before everything
7+
const needPreset = ({ preset } = {}) => preset && !skipPreset.has(preset)
78
const normalizeJestConfig = (config) => ({
89
testMatch: [`**/__tests__/**/*${EXTS}`, `**/?(*.)+(spec|test)${EXTS}`],
910
testEnvironment: 'node',
@@ -65,6 +66,67 @@ export const jestConfig = () => {
6566

6667
// Methods loadJestConfig() and installJestEnvironment() below are for --jest flag
6768

69+
// Optimized out in 'bundle' env
70+
async function loadConfigParts(rawConfig) {
71+
const presetExtension = /\.([cm]?js|json)$/u
72+
const suffixes = ['/jest-preset.json', '/jest-preset.js', '/jest-preset.cjs', '/jest-preset.mjs']
73+
const resolveGlobalSetup = (config, req) => {
74+
if (config.globalSetup) config.globalSetup = req.resolve(config.globalSetup) // eslint-disable-line @exodus/mutable/no-param-reassign-prop-only
75+
if (config.globalTeardown) config.globalTeardown = req.resolve(config.globalTeardown) // eslint-disable-line @exodus/mutable/no-param-reassign-prop-only
76+
}
77+
78+
assert(rawConfig.rootDir)
79+
const { resolve } = await import('node:path')
80+
const { createRequire } = await import('node:module')
81+
const { pathToFileURL } = await import('node:url')
82+
let requireConfig = createRequire(resolve(rawConfig.rootDir, 'package.json'))
83+
resolveGlobalSetup(rawConfig, requireConfig)
84+
while (needPreset(rawConfig)) {
85+
let baseConfig
86+
87+
const attemptLoad = async (file) => {
88+
try {
89+
const resolved = requireConfig.resolve(file)
90+
// FIXME: fix linter to allow this
91+
// const meta = resolved.toLowerCase().endsWith('.json') ? { with: { type: 'json' } } : undefined
92+
// const presetModule = await import(pathToFileURL(resolved), meta)
93+
const presetModule = await import(pathToFileURL(resolved))
94+
requireConfig = createRequire(resolved)
95+
baseConfig = presetModule.default
96+
} catch {}
97+
}
98+
99+
// Even if it is relative, it could be a path to module
100+
for (const suffix of suffixes) {
101+
if (!baseConfig) await attemptLoad(`${rawConfig.preset}${suffix}`)
102+
}
103+
104+
// If it's a path to a file
105+
if (!baseConfig && rawConfig.preset[0] === '.' && presetExtension.test(rawConfig.preset)) {
106+
const { statSync } = await import('node:fs')
107+
if (statSync(rawConfig.preset).isFile()) await attemptLoad(rawConfig.preset)
108+
}
109+
110+
assert(baseConfig, `Could not load preset: ${rawConfig.preset} `)
111+
resolveGlobalSetup(baseConfig, requireConfig)
112+
rawConfig = {
113+
...baseConfig,
114+
...rawConfig,
115+
preset: baseConfig.preset,
116+
setupFiles: [
117+
...(baseConfig.setupFiles || []).map((file) => requireConfig.resolve(file)),
118+
...(rawConfig.setupFiles || []),
119+
],
120+
setupFilesAfterEnv: [
121+
...(baseConfig.setupFilesAfterEnv || []).map((file) => requireConfig.resolve(file)),
122+
...(rawConfig.setupFilesAfterEnv || []),
123+
],
124+
}
125+
}
126+
127+
return rawConfig
128+
}
129+
68130
export async function loadJestConfig(...args) {
69131
let rawConfig
70132
if (process.env.EXODUS_TEST_JEST_CONFIG === undefined) {
@@ -75,67 +137,12 @@ export async function loadJestConfig(...args) {
75137
}
76138

77139
const cleanFile = (file) => file.replace(/^<rootDir>\//g, './') // require is already relative to rootDir
78-
const needPreset = ({ preset } = {}) => preset && !skipPreset.has(preset)
79-
const resolveGlobalSetup = (config, req) => {
80-
if (config.globalSetup) config.globalSetup = req.resolve(config.globalSetup) // eslint-disable-line @exodus/mutable/no-param-reassign-prop-only
81-
if (config.globalTeardown) config.globalTeardown = req.resolve(config.globalTeardown) // eslint-disable-line @exodus/mutable/no-param-reassign-prop-only
82-
}
83-
84-
const presetExtension = /\.([cm]?js|json)$/u
85-
const suffixes = ['/jest-preset.json', '/jest-preset.js', '/jest-preset.cjs', '/jest-preset.mjs']
86140
if (needPreset(rawConfig) || rawConfig?.globalSetup || rawConfig?.globalTeardown) {
87141
rawConfig.preset = cleanFile(rawConfig.preset) // relative to root dir only at top level, presets shouldn't use <rootDir>
88142
if (process.env.EXODUS_TEST_ENVIRONMENT === 'bundle') {
89143
throw new Error('jest preset and globalSetup/Teardown not yet supported in bundles')
90144
} else {
91-
assert(rawConfig.rootDir)
92-
const { resolve } = await import('node:path')
93-
const { createRequire } = await import('node:module')
94-
const { pathToFileURL } = await import('node:url')
95-
let requireConfig = createRequire(resolve(rawConfig.rootDir, 'package.json'))
96-
resolveGlobalSetup(rawConfig, requireConfig)
97-
while (needPreset(rawConfig)) {
98-
let baseConfig
99-
100-
const attemptLoad = async (file) => {
101-
try {
102-
const resolved = requireConfig.resolve(file)
103-
// FIXME: fix linter to allow this
104-
// const meta = resolved.toLowerCase().endsWith('.json') ? { with: { type: 'json' } } : undefined
105-
// const presetModule = await import(pathToFileURL(resolved), meta)
106-
const presetModule = await import(pathToFileURL(resolved))
107-
requireConfig = createRequire(resolved)
108-
baseConfig = presetModule.default
109-
} catch {}
110-
}
111-
112-
// Even if it is relative, it could be a path to module
113-
for (const suffix of suffixes) {
114-
if (!baseConfig) await attemptLoad(`${rawConfig.preset}${suffix}`)
115-
}
116-
117-
// If it's a path to a file
118-
if (!baseConfig && rawConfig.preset[0] === '.' && presetExtension.test(rawConfig.preset)) {
119-
const { statSync } = await import('node:fs')
120-
if (statSync(rawConfig.preset).isFile()) await attemptLoad(rawConfig.preset)
121-
}
122-
123-
assert(baseConfig, `Could not load preset: ${rawConfig.preset} `)
124-
resolveGlobalSetup(baseConfig, requireConfig)
125-
rawConfig = {
126-
...baseConfig,
127-
...rawConfig,
128-
preset: baseConfig.preset,
129-
setupFiles: [
130-
...(baseConfig.setupFiles || []).map((file) => requireConfig.resolve(file)),
131-
...(rawConfig.setupFiles || []),
132-
],
133-
setupFilesAfterEnv: [
134-
...(baseConfig.setupFilesAfterEnv || []).map((file) => requireConfig.resolve(file)),
135-
...(rawConfig.setupFilesAfterEnv || []),
136-
],
137-
}
138-
}
145+
await loadConfigParts(rawConfig)
139146
}
140147
}
141148

@@ -148,6 +155,15 @@ export async function loadJestConfig(...args) {
148155
return config
149156
}
150157

158+
// Optimized out in 'bundle' env
159+
async function makeDynamicImport(rootDir) {
160+
const { resolve } = await import('node:path')
161+
const { createRequire } = await import('node:module')
162+
const { pathToFileURL } = await import('node:url')
163+
const require = createRequire(resolve(rootDir, 'package.json'))
164+
return (path) => import(pathToFileURL(require.resolve(path))) // does not need json imports
165+
}
166+
151167
export async function installJestEnvironment(jestGlobals) {
152168
const engine = await import('./engine.js')
153169

@@ -173,11 +189,7 @@ export async function installJestEnvironment(jestGlobals) {
173189
assert.fail('Requiring non-bundled plugins from bundle is unsupported')
174190
}
175191
} else if (config.rootDir) {
176-
const { resolve } = await import('node:path')
177-
const { createRequire } = await import('node:module')
178-
const { pathToFileURL } = await import('node:url')
179-
const require = createRequire(resolve(config.rootDir, 'package.json'))
180-
dynamicImport = (path) => import(pathToFileURL(require.resolve(path))) // does not need json imports
192+
dynamicImport = makeDynamicImport(config.rootDir)
181193
} else {
182194
dynamicImport = async () => assert.fail('Unreachable: importing plugins without a rootDir')
183195
}

src/jest.mock.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,9 @@ function mockCloneItem(obj, cache) {
253253

254254
// TODO: implement for bundles or add a guard against bundles if __mocks__ dir exists
255255
let loadMocksDirMock
256-
if (process.env.EXODUS_TEST_ENVIRONMENT !== 'bundle') {
256+
257+
// Optimized out in 'bundle' env
258+
function installMockDirs() {
257259
const { existsSync, readdirSync, statSync } = require('node:fs')
258260
const { dirname, join, extname } = require('node:path')
259261
const dirs = []
@@ -305,6 +307,8 @@ if (process.env.EXODUS_TEST_ENVIRONMENT !== 'bundle') {
305307
}
306308
}
307309

310+
if (process.env.EXODUS_TEST_ENVIRONMENT !== 'bundle') installMockDirs()
311+
308312
function jestmock(name, mocker, { override = false, actual, builtin, loc } = {}) {
309313
// Loaded ESM: isn't mocked
310314
// Loaded CJS: mocked via object overriding

0 commit comments

Comments
 (0)