diff --git a/core/test-utils/src/index.ts b/core/test-utils/src/index.ts index 4d06ba191b6d..23cd8724c2b9 100644 --- a/core/test-utils/src/index.ts +++ b/core/test-utils/src/index.ts @@ -28,3 +28,9 @@ export { isReadOnlyPropertyError, requiresStrictArrayPrototypeEquality, } from './runtime'; +export { + type Proxyquire, + type ProxyquireStubs, + createProxyquire, + proxyquire, +} from './proxyquire'; diff --git a/core/test-utils/src/proxyquire.ts b/core/test-utils/src/proxyquire.ts new file mode 100644 index 000000000000..efe8057c5113 --- /dev/null +++ b/core/test-utils/src/proxyquire.ts @@ -0,0 +1,283 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as Module from 'module'; +import * as path from 'path'; +import {fileURLToPath} from 'url'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type ProxyquireStubs = Record; + +export interface Proxyquire { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (request: string, stubs?: ProxyquireStubs): T; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + load(request: string, stubs?: ProxyquireStubs): T; + noCallThru(): Proxyquire; + callThru(): Proxyquire; + noPreserveCache(): Proxyquire; + preserveCache(): Proxyquire; +} + +type ModuleConstructor = { + new (id: string, parent?: NodeModule): NodeModule; + prototype: {require: NodeRequire}; + _cache?: NodeJS.Dict; + _resolveFilename: (request: string, parent: NodeModule) => string; + _nodeModulePaths: (from: string) => string[]; + createRequire?: (filename: string) => NodeRequire; +}; + +const rawMod = ((Module as unknown as {Module?: ModuleConstructor}).Module ?? + Module) as unknown as ModuleConstructor; +const {hasOwnProperty} = Object.prototype; +const isDirectMod = hasOwnProperty.call(rawMod.prototype, 'require'); +const mod: ModuleConstructor = isDirectMod + ? rawMod + : (Object.getPrototypeOf(rawMod) as ModuleConstructor); +const modProto: {require: NodeRequire} = isDirectMod + ? rawMod.prototype + : Object.getPrototypeOf(rawMod.prototype); +const isObj = (o: unknown): o is Record => + Boolean(o && (typeof o === 'object' || typeof o === 'function')); +const hasOwn = (o: unknown, k: string): boolean => + isObj(o) && hasOwnProperty.call(o, k); +const isGlobal = (s: unknown): boolean => + hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); + +const resolveFrom = (base: string, req: string): string => { + try { + return require.resolve(req, {paths: [path.dirname(base)]}); + } catch { + return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; + } +}; + +function getCallerFile(): string | undefined { + const origPrepare = Error.prepareStackTrace; + try { + const err = new Error(); + Error.prepareStackTrace = (_, stack) => stack; + const stack = err.stack as unknown as NodeJS.CallSite[] | undefined; + if (Array.isArray(stack)) { + for (const frame of stack) { + let file = frame.getFileName?.(); + if (file) { + if (file.startsWith('file://')) { + try { + file = fileURLToPath(file); + } catch { + // ignore + } + } + if ( + file !== __filename && + !file.startsWith('node:') && + !file.startsWith('internal/') + ) { + return file; + } + } + } + } + } finally { + Error.prepareStackTrace = origPrepare; + } + return undefined; +} + +function resolveModule(target: NodeModule | string | undefined): NodeModule { + if (target && typeof target === 'object') { + return target; + } + let filename = + typeof target === 'string' ? target : (getCallerFile() ?? __filename); + if (filename.startsWith('file://')) { + try { + filename = fileURLToPath(filename); + } catch { + // ignore + } + } + const cached = require.cache[filename]; + if (cached) { + return cached; + } + const fallback = new mod(filename); + fallback.filename = filename; + fallback.paths = mod._nodeModulePaths(path.dirname(filename)); + return fallback; +} + +interface CallerOptions { + skipCallThru: boolean; + keepCache: boolean; +} + +/** + * Creates a runtime-agnostic `proxyquire` function compatible with both + * Node.js and Bun (`JS_RUNTIME=bun`). + * + * @param caller Optional calling `NodeModule` or `__filename` used to resolve + * relative module paths. When omitted, the caller's filename is detected + * automatically from the call stack. + */ +export function createProxyquire(caller?: NodeModule | string): Proxyquire { + const defaultOpts: CallerOptions = {skipCallThru: false, keepCache: true}; + const callerOpts = new Map(); + + const getOpts = (callerFilename: string): CallerOptions => { + if (caller !== undefined) { + return defaultOpts; + } + let opts = callerOpts.get(callerFilename); + if (!opts) { + opts = {...defaultOpts}; + callerOpts.set(callerFilename, opts); + } + return opts; + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const fn = function proxyquire( + request: string, + stubs: ProxyquireStubs = {}, + ): T { + const parent = resolveModule(caller); + const opts = getOpts(parent.filename); + const sut = mod._resolveFilename(request, parent); + const resolved: ProxyquireStubs = {}; + let global = false; + for (const [k, v] of Object.entries(stubs)) { + if (isGlobal(v)) global = true; + resolved[resolveFrom(sut, k)] = v; + } + const cache = mod._cache ?? require.cache; + const keys = global + ? Object.keys(cache).filter(id => !id.endsWith('.node')) + : [sut]; + const saved = keys.map(id => [id, cache[id]] as const); + for (const id of keys) delete cache[id]; + const prev = modProto.require; + const req = function (this: NodeModule, id: string) { + const isSut = this?.filename === sut; + if (this?.filename && (isSut || global)) { + const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); + const rId = hit ? '' : resolveFrom(this.filename, id); + if (hit || hasOwn(resolved, rId)) { + const stub = hit ? stubs[id] : resolved[rId]; + if (isSut || isGlobal(stub)) { + if (stub === null) { + const e = new Error(`Cannot find module '${id}'`); + throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); + } + const skip = hasOwn(stub, '@noCallThru') + ? Boolean(stub['@noCallThru']) + : opts.skipCallThru; + if (!skip && isObj(stub)) { + try { + const real = prev.call(this, id); + if (isObj(real)) { + return new Proxy(stub, { + get(target, prop) { + if (prop in target) { + return Reflect.get(target, prop); + } + return Reflect.get(real, prop); + }, + has(target, prop) { + return prop in target || prop in real; + }, + ownKeys(target) { + return Array.from( + new Set([ + ...Reflect.ownKeys(target), + ...Reflect.ownKeys(real), + ]), + ); + }, + getOwnPropertyDescriptor(target, prop) { + const targetDesc = Reflect.getOwnPropertyDescriptor( + target, + prop, + ); + if (targetDesc) { + return targetDesc; + } + const realDesc = Reflect.getOwnPropertyDescriptor( + real, + prop, + ); + return realDesc + ? {...realDesc, configurable: true} + : undefined; + }, + }); + } + } catch { + // ignore when underlying module cannot be loaded + } + } + return stub; + } + } + } + return prev.call(this, id); + }; + modProto.require = Object.assign(req, prev); + try { + return typeof parent.require === 'function' && parent instanceof mod + ? prev.call(parent, request) + : mod.createRequire + ? mod.createRequire(parent.filename)(request) + : prev.call(parent, request); + } finally { + modProto.require = prev; + const savedMap = new Map(saved); + for (const id of global ? Object.keys(cache) : [sut]) { + if (!id.endsWith('.node')) { + const original = savedMap.get(id); + if (!opts.keepCache || id !== sut || original !== undefined) { + delete cache[id]; + } + } + } + for (const [id, m] of saved) { + if (m && (opts.keepCache || id !== sut)) cache[id] = m; + } + } + }; + + const updateOpts = (patch: Partial): Proxyquire => { + const parent = resolveModule(caller); + Object.assign(getOpts(parent.filename), patch); + return instance; + }; + + const instance: Proxyquire = Object.assign(fn, { + load: fn, + noCallThru: () => updateOpts({skipCallThru: true}), + callThru: () => updateOpts({skipCallThru: false}), + noPreserveCache: () => updateOpts({keepCache: false}), + preserveCache: () => updateOpts({keepCache: true}), + }); + + return instance; +} + +/** + * Shared `proxyquire` instance that resolves relative module requests and + * option flags (`noCallThru`, `noPreserveCache`, etc.) per calling test file. + */ +export const proxyquire: Proxyquire = createProxyquire(); diff --git a/core/test-utils/test/proxyquire.test.ts b/core/test-utils/test/proxyquire.test.ts new file mode 100644 index 000000000000..c69fe4b93772 --- /dev/null +++ b/core/test-utils/test/proxyquire.test.ts @@ -0,0 +1,198 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as fs from 'fs'; +import * as Module from 'module'; +import * as os from 'os'; +import * as path from 'path'; +import {pathToFileURL} from 'url'; +import {createProxyquire, proxyquire} from '../src'; + +describe('proxyquire utilities (unit)', () => { + let tmpDir: string; + let depFile: string; + let sutFile: string; + let transitiveFile: string; + + beforeAll(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'proxyquire-test-')); + depFile = path.join(tmpDir, 'dep.js'); + transitiveFile = path.join(tmpDir, 'transitive.js'); + sutFile = path.join(tmpDir, 'sut.js'); + + fs.writeFileSync( + depFile, + [ + 'module.exports = {', + ' greet: () => "real-greet",', + ' extra: () => "real-extra",', + ' constant: 42,', + '};', + ].join('\n'), + ); + fs.writeFileSync( + transitiveFile, + [ + 'const dep = require("./dep");', + 'module.exports = { run: () => dep.greet() };', + ].join('\n'), + ); + fs.writeFileSync( + sutFile, + [ + 'const dep = require("./dep");', + 'const trans = require("./transitive");', + 'const pathMod = require("path");', + 'module.exports = {', + ' greet: () => dep.greet(),', + ' extra: () => dep.extra && dep.extra(),', + ' constant: dep.constant,', + ' hasExtra: "extra" in dep,', + ' keys: Object.keys(dep),', + ' transGreet: () => trans.run(),', + ' sep: pathMod.sep,', + '};', + ].join('\n'), + ); + }); + + afterAll(() => { + fs.rmSync(tmpDir, {recursive: true, force: true}); + }); + + it('stubs direct dependencies and falls through to real module via Proxy without mutating stub', () => { + const stub = {greet: () => 'stubbed-greet'}; + const loaded = proxyquire(sutFile, {'./dep': stub}); + expect(loaded.greet()).toBe('stubbed-greet'); + expect(loaded.extra()).toBe('real-extra'); + expect(loaded.constant).toBe(42); + expect(loaded.hasExtra).toBe(true); + expect(loaded.keys).toEqual( + expect.arrayContaining(['greet', 'extra', 'constant']), + ); + // Stub object itself was not mutated in place + expect('extra' in stub).toBe(false); + expect(Object.keys(stub)).toEqual(['greet']); + }); + + it('supports @noCallThru on individual stubs and noCallThru() / callThru() on instance', () => { + const pq = createProxyquire(__filename); + const stubWithNoCallThru = { + greet: () => 'isolated', + '@noCallThru': true, + }; + const loaded1 = pq.load(sutFile, {'./dep': stubWithNoCallThru}); + expect(loaded1.greet()).toBe('isolated'); + expect(loaded1.extra()).toBeUndefined(); + expect(loaded1.constant).toBeUndefined(); + + pq.noCallThru(); + const loaded2 = pq(sutFile, {'./dep': {greet: () => 'instance-no-call'}}); + expect(loaded2.greet()).toBe('instance-no-call'); + expect(loaded2.extra()).toBeUndefined(); + + pq.callThru(); + const loaded3 = pq(sutFile, {'./dep': {greet: () => 'instance-call-thru'}}); + expect(loaded3.greet()).toBe('instance-call-thru'); + expect(loaded3.extra()).toBe('real-extra'); + }); + + it('supports @global stubs across transitive dependencies', () => { + const loadedNonGlobal = proxyquire(sutFile, { + './dep': {greet: () => 'direct-only'}, + }); + expect(loadedNonGlobal.greet()).toBe('direct-only'); + + const loadedGlobal = proxyquire(sutFile, { + './dep': {greet: () => 'global-stub', '@global': true}, + }); + expect(loadedGlobal.greet()).toBe('global-stub'); + expect(loadedGlobal.transGreet()).toBe('global-stub'); + }); + + it('throws MODULE_NOT_FOUND when stub is null', () => { + expect(() => proxyquire(sutFile, {'./dep': null})).toThrow( + /Cannot find module '\.\/dep'/, + ); + }); + + it('supports noPreserveCache() and preserveCache()', () => { + const rawMod = (( + Module as unknown as {Module?: {_cache?: NodeJS.Dict}} + ).Module ?? Module) as {_cache?: NodeJS.Dict}; + const modCache = + rawMod._cache ?? + (Object.getPrototypeOf(rawMod) as {_cache?: NodeJS.Dict}) + ?._cache ?? + require.cache; + const pq = createProxyquire(module); + pq.noPreserveCache(); + const loaded1 = pq(sutFile, {'./dep': {greet: () => 'a'}}); + expect(loaded1.greet()).toBe('a'); + expect(modCache[sutFile]).toBeUndefined(); + + pq.preserveCache(); + const loaded2 = pq(sutFile, {'./dep': {greet: () => 'b'}}); + expect(loaded2.greet()).toBe('b'); + expect(modCache[sutFile]).toBeDefined(); + }); + + it('respects Proxy getOwnPropertyDescriptor invariants for non-configurable stub properties', () => { + const fnStub = Object.assign(function customFn() {}, { + greet: () => 'fn-greet', + }); + Object.defineProperty(fnStub, 'locked', { + value: 123, + configurable: false, + enumerable: true, + }); + const depCheckFile = path.join(tmpDir, 'dep-check.js'); + fs.writeFileSync( + depCheckFile, + [ + 'const dep = require("./dep");', + 'module.exports = {', + ' protoDesc: Object.getOwnPropertyDescriptor(dep, "prototype"),', + ' lockedDesc: Object.getOwnPropertyDescriptor(dep, "locked"),', + ' extraDesc: Object.getOwnPropertyDescriptor(dep, "extra"),', + ' missingDesc: Object.getOwnPropertyDescriptor(dep, "nonExistent"),', + ' keys: Object.keys(dep),', + '};', + ].join('\n'), + ); + const loaded = proxyquire(depCheckFile, {'./dep': fnStub}); + expect(loaded.protoDesc?.configurable).toBe(false); + expect(loaded.lockedDesc?.configurable).toBe(false); + expect(loaded.lockedDesc?.value).toBe(123); + expect(loaded.extraDesc?.configurable).toBe(true); + expect(loaded.missingDesc).toBeUndefined(); + expect(loaded.keys).toEqual( + expect.arrayContaining(['greet', 'locked', 'extra', 'constant']), + ); + }); + + it('supports bare module stubs and unresolvable relative paths', () => { + const loaded = proxyquire(sutFile, { + path: {sep: '/custom-sep'}, + './non-existent-relative': {foo: 'bar'}, + }); + expect(loaded.sep).toBe('/custom-sep'); + }); + + it('normalizes file:// URLs passed to createProxyquire or returned by stack frames', () => { + const pqFromUrl = createProxyquire(pathToFileURL(sutFile).href); + const loaded = pqFromUrl('./sut', {'./dep': {greet: () => 'url-caller'}}); + expect(loaded.greet()).toBe('url-caller'); + }); +});