| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import type {MeasureMemoryOptions} from 'node:vm'; |
| 9 | import type {Json} from './typeUtils'; |
| 10 | |
| 11 | import {measureMemory} from 'node:vm'; |
| 12 | import {Logger} from '../isl-server/src/logger'; |
| 13 | |
| 14 | export class MockLogger extends Logger { |
| 15 | write() { |
| 16 | // noop |
| 17 | } |
| 18 | } |
| 19 | export const mockLogger = new MockLogger(); |
| 20 | |
| 21 | export function clone<T extends Json>(o: T): T { |
| 22 | return JSON.parse(JSON.stringify(o)); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Returns a Promise which resolves after the current async tick is finished. |
| 27 | * Useful for testing code which `await`s. |
| 28 | */ |
| 29 | export function nextTick(): Promise<void> { |
| 30 | return new Promise(res => setTimeout(res, 0)); |
| 31 | } |
| 32 | |
| 33 | export async function gc() { |
| 34 | // 'node --expose-gc' defines 'global.gc'. |
| 35 | // To run with yarn: yarn node --expose-gc ./node_modules/.bin/jest ... |
| 36 | const globalGc = global.gc; |
| 37 | if (globalGc != null) { |
| 38 | await new Promise<void>(r => |
| 39 | setTimeout(() => { |
| 40 | globalGc(); |
| 41 | r(); |
| 42 | }, 0), |
| 43 | ); |
| 44 | } else { |
| 45 | // measureMemory with 'eager' has a side effect of running the GC. |
| 46 | // This exists since node 14. |
| 47 | // 'as' used since `MeasureMemoryOptions` is outdated (node 13?). |
| 48 | await measureMemory({execution: 'eager'} as MeasureMemoryOptions); |
| 49 | } |
| 50 | } |
| 51 | |