60c6044c9efd1c08d650105d8e59abbb46e02f34bc5d0dcf29b3743f8c4b495b76dd2bf75d47a5ae0a875cd2a70d46c1713ffbad09c188517c59e817210710 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /**
  2. * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using:
  3. *
  4. * ```js
  5. * import v8 from 'node:v8';
  6. * ```
  7. * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/v8.js)
  8. */
  9. declare module "v8" {
  10. import { Readable } from "node:stream";
  11. interface HeapSpaceInfo {
  12. space_name: string;
  13. space_size: number;
  14. space_used_size: number;
  15. space_available_size: number;
  16. physical_space_size: number;
  17. }
  18. // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */
  19. type DoesZapCodeSpaceFlag = 0 | 1;
  20. interface HeapInfo {
  21. total_heap_size: number;
  22. total_heap_size_executable: number;
  23. total_physical_size: number;
  24. total_available_size: number;
  25. used_heap_size: number;
  26. heap_size_limit: number;
  27. malloced_memory: number;
  28. peak_malloced_memory: number;
  29. does_zap_garbage: DoesZapCodeSpaceFlag;
  30. number_of_native_contexts: number;
  31. number_of_detached_contexts: number;
  32. total_global_handles_size: number;
  33. used_global_handles_size: number;
  34. external_memory: number;
  35. }
  36. interface HeapCodeStatistics {
  37. code_and_metadata_size: number;
  38. bytecode_and_metadata_size: number;
  39. external_script_source_size: number;
  40. }
  41. interface HeapSnapshotOptions {
  42. /**
  43. * If true, expose internals in the heap snapshot.
  44. * @default false
  45. */
  46. exposeInternals?: boolean;
  47. /**
  48. * If true, expose numeric values in artificial fields.
  49. * @default false
  50. */
  51. exposeNumericValues?: boolean;
  52. }
  53. /**
  54. * Returns an integer representing a version tag derived from the V8 version,
  55. * command-line flags, and detected CPU features. This is useful for determining
  56. * whether a `vm.Script` `cachedData` buffer is compatible with this instance
  57. * of V8.
  58. *
  59. * ```js
  60. * console.log(v8.cachedDataVersionTag()); // 3947234607
  61. * // The value returned by v8.cachedDataVersionTag() is derived from the V8
  62. * // version, command-line flags, and detected CPU features. Test that the value
  63. * // does indeed update when flags are toggled.
  64. * v8.setFlagsFromString('--allow_natives_syntax');
  65. * console.log(v8.cachedDataVersionTag()); // 183726201
  66. * ```
  67. * @since v8.0.0
  68. */
  69. function cachedDataVersionTag(): number;
  70. /**
  71. * Returns an object with the following properties:
  72. *
  73. * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap
  74. * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger
  75. * because it continuously touches all heap pages and that makes them less likely
  76. * to get swapped out by the operating system.
  77. *
  78. * `number_of_native_contexts` The value of native\_context is the number of the
  79. * top-level contexts currently active. Increase of this number over time indicates
  80. * a memory leak.
  81. *
  82. * `number_of_detached_contexts` The value of detached\_context is the number
  83. * of contexts that were detached and not yet garbage collected. This number
  84. * being non-zero indicates a potential memory leak.
  85. *
  86. * `total_global_handles_size` The value of total\_global\_handles\_size is the
  87. * total memory size of V8 global handles.
  88. *
  89. * `used_global_handles_size` The value of used\_global\_handles\_size is the
  90. * used memory size of V8 global handles.
  91. *
  92. * `external_memory` The value of external\_memory is the memory size of array
  93. * buffers and external strings.
  94. *
  95. * ```js
  96. * {
  97. * total_heap_size: 7326976,
  98. * total_heap_size_executable: 4194304,
  99. * total_physical_size: 7326976,
  100. * total_available_size: 1152656,
  101. * used_heap_size: 3476208,
  102. * heap_size_limit: 1535115264,
  103. * malloced_memory: 16384,
  104. * peak_malloced_memory: 1127496,
  105. * does_zap_garbage: 0,
  106. * number_of_native_contexts: 1,
  107. * number_of_detached_contexts: 0,
  108. * total_global_handles_size: 8192,
  109. * used_global_handles_size: 3296,
  110. * external_memory: 318824
  111. * }
  112. * ```
  113. * @since v1.0.0
  114. */
  115. function getHeapStatistics(): HeapInfo;
  116. /**
  117. * It returns an object with a structure similar to the
  118. * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html)
  119. * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html)
  120. * for more information about the properties of the object.
  121. *
  122. * ```js
  123. * // Detailed
  124. * ({
  125. * committed_size_bytes: 131072,
  126. * resident_size_bytes: 131072,
  127. * used_size_bytes: 152,
  128. * space_statistics: [
  129. * {
  130. * name: 'NormalPageSpace0',
  131. * committed_size_bytes: 0,
  132. * resident_size_bytes: 0,
  133. * used_size_bytes: 0,
  134. * page_stats: [{}],
  135. * free_list_stats: {},
  136. * },
  137. * {
  138. * name: 'NormalPageSpace1',
  139. * committed_size_bytes: 131072,
  140. * resident_size_bytes: 131072,
  141. * used_size_bytes: 152,
  142. * page_stats: [{}],
  143. * free_list_stats: {},
  144. * },
  145. * {
  146. * name: 'NormalPageSpace2',
  147. * committed_size_bytes: 0,
  148. * resident_size_bytes: 0,
  149. * used_size_bytes: 0,
  150. * page_stats: [{}],
  151. * free_list_stats: {},
  152. * },
  153. * {
  154. * name: 'NormalPageSpace3',
  155. * committed_size_bytes: 0,
  156. * resident_size_bytes: 0,
  157. * used_size_bytes: 0,
  158. * page_stats: [{}],
  159. * free_list_stats: {},
  160. * },
  161. * {
  162. * name: 'LargePageSpace',
  163. * committed_size_bytes: 0,
  164. * resident_size_bytes: 0,
  165. * used_size_bytes: 0,
  166. * page_stats: [{}],
  167. * free_list_stats: {},
  168. * },
  169. * ],
  170. * type_names: [],
  171. * detail_level: 'detailed',
  172. * });
  173. * ```
  174. *
  175. * ```js
  176. * // Brief
  177. * ({
  178. * committed_size_bytes: 131072,
  179. * resident_size_bytes: 131072,
  180. * used_size_bytes: 128864,
  181. * space_statistics: [],
  182. * type_names: [],
  183. * detail_level: 'brief',
  184. * });
  185. * ```
  186. * @since v22.15.0
  187. * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics.
  188. * Accepted values are:
  189. * * `'brief'`: Brief statistics contain only the top-level
  190. * allocated and used
  191. * memory statistics for the entire heap.
  192. * * `'detailed'`: Detailed statistics also contain a break
  193. * down per space and page, as well as freelist statistics
  194. * and object type histograms.
  195. */
  196. function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object;
  197. /**
  198. * Returns statistics about the V8 heap spaces, i.e. the segments which make up
  199. * the V8 heap. Neither the ordering of heap spaces, nor the availability of a
  200. * heap space can be guaranteed as the statistics are provided via the
  201. * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the
  202. * next.
  203. *
  204. * The value returned is an array of objects containing the following properties:
  205. *
  206. * ```json
  207. * [
  208. * {
  209. * "space_name": "new_space",
  210. * "space_size": 2063872,
  211. * "space_used_size": 951112,
  212. * "space_available_size": 80824,
  213. * "physical_space_size": 2063872
  214. * },
  215. * {
  216. * "space_name": "old_space",
  217. * "space_size": 3090560,
  218. * "space_used_size": 2493792,
  219. * "space_available_size": 0,
  220. * "physical_space_size": 3090560
  221. * },
  222. * {
  223. * "space_name": "code_space",
  224. * "space_size": 1260160,
  225. * "space_used_size": 644256,
  226. * "space_available_size": 960,
  227. * "physical_space_size": 1260160
  228. * },
  229. * {
  230. * "space_name": "map_space",
  231. * "space_size": 1094160,
  232. * "space_used_size": 201608,
  233. * "space_available_size": 0,
  234. * "physical_space_size": 1094160
  235. * },
  236. * {
  237. * "space_name": "large_object_space",
  238. * "space_size": 0,
  239. * "space_used_size": 0,
  240. * "space_available_size": 1490980608,
  241. * "physical_space_size": 0
  242. * }
  243. * ]
  244. * ```
  245. * @since v6.0.0
  246. */
  247. function getHeapSpaceStatistics(): HeapSpaceInfo[];
  248. /**
  249. * The `v8.setFlagsFromString()` method can be used to programmatically set
  250. * V8 command-line flags. This method should be used with care. Changing settings
  251. * after the VM has started may result in unpredictable behavior, including
  252. * crashes and data loss; or it may simply do nothing.
  253. *
  254. * The V8 options available for a version of Node.js may be determined by running `node --v8-options`.
  255. *
  256. * Usage:
  257. *
  258. * ```js
  259. * // Print GC events to stdout for one minute.
  260. * import v8 from 'node:v8';
  261. * v8.setFlagsFromString('--trace_gc');
  262. * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
  263. * ```
  264. * @since v1.0.0
  265. */
  266. function setFlagsFromString(flags: string): void;
  267. /**
  268. * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function)
  269. * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain
  270. * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should
  271. * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the
  272. * application.
  273. *
  274. * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects
  275. * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided
  276. * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the
  277. * target objects during the search.
  278. *
  279. * Only objects created in the current execution context are included in the results.
  280. *
  281. * ```js
  282. * import { queryObjects } from 'node:v8';
  283. * class A { foo = 'bar'; }
  284. * console.log(queryObjects(A)); // 0
  285. * const a = new A();
  286. * console.log(queryObjects(A)); // 1
  287. * // [ "A { foo: 'bar' }" ]
  288. * console.log(queryObjects(A, { format: 'summary' }));
  289. *
  290. * class B extends A { bar = 'qux'; }
  291. * const b = new B();
  292. * console.log(queryObjects(B)); // 1
  293. * // [ "B { foo: 'bar', bar: 'qux' }" ]
  294. * console.log(queryObjects(B, { format: 'summary' }));
  295. *
  296. * // Note that, when there are child classes inheriting from a constructor,
  297. * // the constructor also shows up in the prototype chain of the child
  298. * // classes's prototoype, so the child classes's prototoype would also be
  299. * // included in the result.
  300. * console.log(queryObjects(A)); // 3
  301. * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]
  302. * console.log(queryObjects(A, { format: 'summary' }));
  303. * ```
  304. * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap.
  305. * @since v20.13.0
  306. * @experimental
  307. */
  308. function queryObjects(ctor: Function): number | string[];
  309. function queryObjects(ctor: Function, options: { format: "count" }): number;
  310. function queryObjects(ctor: Function, options: { format: "summary" }): string[];
  311. /**
  312. * Generates a snapshot of the current V8 heap and returns a Readable
  313. * Stream that may be used to read the JSON serialized representation.
  314. * This JSON stream format is intended to be used with tools such as
  315. * Chrome DevTools. The JSON schema is undocumented and specific to the
  316. * V8 engine. Therefore, the schema may change from one version of V8 to the next.
  317. *
  318. * Creating a heap snapshot requires memory about twice the size of the heap at
  319. * the time the snapshot is created. This results in the risk of OOM killers
  320. * terminating the process.
  321. *
  322. * Generating a snapshot is a synchronous operation which blocks the event loop
  323. * for a duration depending on the heap size.
  324. *
  325. * ```js
  326. * // Print heap snapshot to the console
  327. * import v8 from 'node:v8';
  328. * const stream = v8.getHeapSnapshot();
  329. * stream.pipe(process.stdout);
  330. * ```
  331. * @since v11.13.0
  332. * @return A Readable containing the V8 heap snapshot.
  333. */
  334. function getHeapSnapshot(options?: HeapSnapshotOptions): Readable;
  335. /**
  336. * Generates a snapshot of the current V8 heap and writes it to a JSON
  337. * file. This file is intended to be used with tools such as Chrome
  338. * DevTools. The JSON schema is undocumented and specific to the V8
  339. * engine, and may change from one version of V8 to the next.
  340. *
  341. * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will
  342. * not contain any information about the workers, and vice versa.
  343. *
  344. * Creating a heap snapshot requires memory about twice the size of the heap at
  345. * the time the snapshot is created. This results in the risk of OOM killers
  346. * terminating the process.
  347. *
  348. * Generating a snapshot is a synchronous operation which blocks the event loop
  349. * for a duration depending on the heap size.
  350. *
  351. * ```js
  352. * import { writeHeapSnapshot } from 'node:v8';
  353. * import {
  354. * Worker,
  355. * isMainThread,
  356. * parentPort,
  357. * } from 'node:worker_threads';
  358. *
  359. * if (isMainThread) {
  360. * const worker = new Worker(__filename);
  361. *
  362. * worker.once('message', (filename) => {
  363. * console.log(`worker heapdump: ${filename}`);
  364. * // Now get a heapdump for the main thread.
  365. * console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
  366. * });
  367. *
  368. * // Tell the worker to create a heapdump.
  369. * worker.postMessage('heapdump');
  370. * } else {
  371. * parentPort.once('message', (message) => {
  372. * if (message === 'heapdump') {
  373. * // Generate a heapdump for the worker
  374. * // and return the filename to the parent.
  375. * parentPort.postMessage(writeHeapSnapshot());
  376. * }
  377. * });
  378. * }
  379. * ```
  380. * @since v11.13.0
  381. * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be
  382. * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a
  383. * worker thread.
  384. * @return The filename where the snapshot was saved.
  385. */
  386. function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string;
  387. /**
  388. * Get statistics about code and its metadata in the heap, see
  389. * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the
  390. * following properties:
  391. *
  392. * ```js
  393. * {
  394. * code_and_metadata_size: 212208,
  395. * bytecode_and_metadata_size: 161368,
  396. * external_script_source_size: 1410794,
  397. * cpu_profiler_metadata_size: 0,
  398. * }
  399. * ```
  400. * @since v12.8.0
  401. */
  402. function getHeapCodeStatistics(): HeapCodeStatistics;
  403. /**
  404. * @since v8.0.0
  405. */
  406. class Serializer {
  407. /**
  408. * Writes out a header, which includes the serialization format version.
  409. */
  410. writeHeader(): void;
  411. /**
  412. * Serializes a JavaScript value and adds the serialized representation to the
  413. * internal buffer.
  414. *
  415. * This throws an error if `value` cannot be serialized.
  416. */
  417. writeValue(val: any): boolean;
  418. /**
  419. * Returns the stored internal buffer. This serializer should not be used once
  420. * the buffer is released. Calling this method results in undefined behavior
  421. * if a previous write has failed.
  422. */
  423. releaseBuffer(): Buffer;
  424. /**
  425. * Marks an `ArrayBuffer` as having its contents transferred out of band.
  426. * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`.
  427. * @param id A 32-bit unsigned integer.
  428. * @param arrayBuffer An `ArrayBuffer` instance.
  429. */
  430. transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;
  431. /**
  432. * Write a raw 32-bit unsigned integer.
  433. * For use inside of a custom `serializer._writeHostObject()`.
  434. */
  435. writeUint32(value: number): void;
  436. /**
  437. * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.
  438. * For use inside of a custom `serializer._writeHostObject()`.
  439. */
  440. writeUint64(hi: number, lo: number): void;
  441. /**
  442. * Write a JS `number` value.
  443. * For use inside of a custom `serializer._writeHostObject()`.
  444. */
  445. writeDouble(value: number): void;
  446. /**
  447. * Write raw bytes into the serializer's internal buffer. The deserializer
  448. * will require a way to compute the length of the buffer.
  449. * For use inside of a custom `serializer._writeHostObject()`.
  450. */
  451. writeRawBytes(buffer: NodeJS.TypedArray): void;
  452. }
  453. /**
  454. * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only
  455. * stores the part of their underlying `ArrayBuffer`s that they are referring to.
  456. * @since v8.0.0
  457. */
  458. class DefaultSerializer extends Serializer {}
  459. /**
  460. * @since v8.0.0
  461. */
  462. class Deserializer {
  463. constructor(data: NodeJS.TypedArray);
  464. /**
  465. * Reads and validates a header (including the format version).
  466. * May, for example, reject an invalid or unsupported wire format. In that case,
  467. * an `Error` is thrown.
  468. */
  469. readHeader(): boolean;
  470. /**
  471. * Deserializes a JavaScript value from the buffer and returns it.
  472. */
  473. readValue(): any;
  474. /**
  475. * Marks an `ArrayBuffer` as having its contents transferred out of band.
  476. * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of
  477. * `SharedArrayBuffer`s).
  478. * @param id A 32-bit unsigned integer.
  479. * @param arrayBuffer An `ArrayBuffer` instance.
  480. */
  481. transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;
  482. /**
  483. * Reads the underlying wire format version. Likely mostly to be useful to
  484. * legacy code reading old wire format versions. May not be called before `.readHeader()`.
  485. */
  486. getWireFormatVersion(): number;
  487. /**
  488. * Read a raw 32-bit unsigned integer and return it.
  489. * For use inside of a custom `deserializer._readHostObject()`.
  490. */
  491. readUint32(): number;
  492. /**
  493. * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries.
  494. * For use inside of a custom `deserializer._readHostObject()`.
  495. */
  496. readUint64(): [number, number];
  497. /**
  498. * Read a JS `number` value.
  499. * For use inside of a custom `deserializer._readHostObject()`.
  500. */
  501. readDouble(): number;
  502. /**
  503. * Read raw bytes from the deserializer's internal buffer. The `length` parameter
  504. * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`.
  505. * For use inside of a custom `deserializer._readHostObject()`.
  506. */
  507. readRawBytes(length: number): Buffer;
  508. }
  509. /**
  510. * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`.
  511. * @since v8.0.0
  512. */
  513. class DefaultDeserializer extends Deserializer {}
  514. /**
  515. * Uses a `DefaultSerializer` to serialize `value` into a buffer.
  516. *
  517. * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to
  518. * serialize a huge object which requires buffer
  519. * larger than `buffer.constants.MAX_LENGTH`.
  520. * @since v8.0.0
  521. */
  522. function serialize(value: any): Buffer;
  523. /**
  524. * Uses a `DefaultDeserializer` with default options to read a JS value
  525. * from a buffer.
  526. * @since v8.0.0
  527. * @param buffer A buffer returned by {@link serialize}.
  528. */
  529. function deserialize(buffer: NodeJS.ArrayBufferView): any;
  530. /**
  531. * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple
  532. * times during the lifetime of the process. Each time the execution counter will
  533. * be reset and a new coverage report will be written to the directory specified
  534. * by `NODE_V8_COVERAGE`.
  535. *
  536. * When the process is about to exit, one last coverage will still be written to
  537. * disk unless {@link stopCoverage} is invoked before the process exits.
  538. * @since v15.1.0, v14.18.0, v12.22.0
  539. */
  540. function takeCoverage(): void;
  541. /**
  542. * The `v8.stopCoverage()` method allows the user to stop the coverage collection
  543. * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count
  544. * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand.
  545. * @since v15.1.0, v14.18.0, v12.22.0
  546. */
  547. function stopCoverage(): void;
  548. /**
  549. * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once.
  550. * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information.
  551. * @experimental
  552. * @since v18.10.0, v16.18.0
  553. */
  554. function setHeapSnapshotNearHeapLimit(limit: number): void;
  555. /**
  556. * This API collects GC data in current thread.
  557. * @since v19.6.0, v18.15.0
  558. */
  559. class GCProfiler {
  560. /**
  561. * Start collecting GC data.
  562. * @since v19.6.0, v18.15.0
  563. */
  564. start(): void;
  565. /**
  566. * Stop collecting GC data and return an object. The content of object
  567. * is as follows.
  568. *
  569. * ```json
  570. * {
  571. * "version": 1,
  572. * "startTime": 1674059033862,
  573. * "statistics": [
  574. * {
  575. * "gcType": "Scavenge",
  576. * "beforeGC": {
  577. * "heapStatistics": {
  578. * "totalHeapSize": 5005312,
  579. * "totalHeapSizeExecutable": 524288,
  580. * "totalPhysicalSize": 5226496,
  581. * "totalAvailableSize": 4341325216,
  582. * "totalGlobalHandlesSize": 8192,
  583. * "usedGlobalHandlesSize": 2112,
  584. * "usedHeapSize": 4883840,
  585. * "heapSizeLimit": 4345298944,
  586. * "mallocedMemory": 254128,
  587. * "externalMemory": 225138,
  588. * "peakMallocedMemory": 181760
  589. * },
  590. * "heapSpaceStatistics": [
  591. * {
  592. * "spaceName": "read_only_space",
  593. * "spaceSize": 0,
  594. * "spaceUsedSize": 0,
  595. * "spaceAvailableSize": 0,
  596. * "physicalSpaceSize": 0
  597. * }
  598. * ]
  599. * },
  600. * "cost": 1574.14,
  601. * "afterGC": {
  602. * "heapStatistics": {
  603. * "totalHeapSize": 6053888,
  604. * "totalHeapSizeExecutable": 524288,
  605. * "totalPhysicalSize": 5500928,
  606. * "totalAvailableSize": 4341101384,
  607. * "totalGlobalHandlesSize": 8192,
  608. * "usedGlobalHandlesSize": 2112,
  609. * "usedHeapSize": 4059096,
  610. * "heapSizeLimit": 4345298944,
  611. * "mallocedMemory": 254128,
  612. * "externalMemory": 225138,
  613. * "peakMallocedMemory": 181760
  614. * },
  615. * "heapSpaceStatistics": [
  616. * {
  617. * "spaceName": "read_only_space",
  618. * "spaceSize": 0,
  619. * "spaceUsedSize": 0,
  620. * "spaceAvailableSize": 0,
  621. * "physicalSpaceSize": 0
  622. * }
  623. * ]
  624. * }
  625. * }
  626. * ],
  627. * "endTime": 1674059036865
  628. * }
  629. * ```
  630. *
  631. * Here's an example.
  632. *
  633. * ```js
  634. * import { GCProfiler } from 'node:v8';
  635. * const profiler = new GCProfiler();
  636. * profiler.start();
  637. * setTimeout(() => {
  638. * console.log(profiler.stop());
  639. * }, 1000);
  640. * ```
  641. * @since v19.6.0, v18.15.0
  642. */
  643. stop(): GCProfilerResult;
  644. }
  645. interface GCProfilerResult {
  646. version: number;
  647. startTime: number;
  648. endTime: number;
  649. statistics: Array<{
  650. gcType: string;
  651. cost: number;
  652. beforeGC: {
  653. heapStatistics: HeapStatistics;
  654. heapSpaceStatistics: HeapSpaceStatistics[];
  655. };
  656. afterGC: {
  657. heapStatistics: HeapStatistics;
  658. heapSpaceStatistics: HeapSpaceStatistics[];
  659. };
  660. }>;
  661. }
  662. interface HeapStatistics {
  663. totalHeapSize: number;
  664. totalHeapSizeExecutable: number;
  665. totalPhysicalSize: number;
  666. totalAvailableSize: number;
  667. totalGlobalHandlesSize: number;
  668. usedGlobalHandlesSize: number;
  669. usedHeapSize: number;
  670. heapSizeLimit: number;
  671. mallocedMemory: number;
  672. externalMemory: number;
  673. peakMallocedMemory: number;
  674. }
  675. interface HeapSpaceStatistics {
  676. spaceName: string;
  677. spaceSize: number;
  678. spaceUsedSize: number;
  679. spaceAvailableSize: number;
  680. physicalSpaceSize: number;
  681. }
  682. /**
  683. * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will
  684. * happen if a promise is created without ever getting a continuation.
  685. * @since v17.1.0, v16.14.0
  686. * @param promise The promise being created.
  687. * @param parent The promise continued from, if applicable.
  688. */
  689. interface Init {
  690. (promise: Promise<unknown>, parent: Promise<unknown>): void;
  691. }
  692. /**
  693. * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming.
  694. *
  695. * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise.
  696. * The before callback may be called many times in the case where many continuations have been made from the same promise.
  697. * @since v17.1.0, v16.14.0
  698. */
  699. interface Before {
  700. (promise: Promise<unknown>): void;
  701. }
  702. /**
  703. * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await.
  704. * @since v17.1.0, v16.14.0
  705. */
  706. interface After {
  707. (promise: Promise<unknown>): void;
  708. }
  709. /**
  710. * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or
  711. * {@link Promise.reject()}.
  712. * @since v17.1.0, v16.14.0
  713. */
  714. interface Settled {
  715. (promise: Promise<unknown>): void;
  716. }
  717. /**
  718. * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or
  719. * around an await, and when the promise resolves or rejects.
  720. *
  721. * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and
  722. * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop.
  723. * @since v17.1.0, v16.14.0
  724. */
  725. interface HookCallbacks {
  726. init?: Init;
  727. before?: Before;
  728. after?: After;
  729. settled?: Settled;
  730. }
  731. interface PromiseHooks {
  732. /**
  733. * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
  734. * @since v17.1.0, v16.14.0
  735. * @param init The {@link Init | `init` callback} to call when a promise is created.
  736. * @return Call to stop the hook.
  737. */
  738. onInit: (init: Init) => Function;
  739. /**
  740. * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
  741. * @since v17.1.0, v16.14.0
  742. * @param settled The {@link Settled | `settled` callback} to call when a promise is created.
  743. * @return Call to stop the hook.
  744. */
  745. onSettled: (settled: Settled) => Function;
  746. /**
  747. * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
  748. * @since v17.1.0, v16.14.0
  749. * @param before The {@link Before | `before` callback} to call before a promise continuation executes.
  750. * @return Call to stop the hook.
  751. */
  752. onBefore: (before: Before) => Function;
  753. /**
  754. * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
  755. * @since v17.1.0, v16.14.0
  756. * @param after The {@link After | `after` callback} to call after a promise continuation executes.
  757. * @return Call to stop the hook.
  758. */
  759. onAfter: (after: After) => Function;
  760. /**
  761. * Registers functions to be called for different lifetime events of each promise.
  762. * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime.
  763. * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed.
  764. * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop.
  765. * @since v17.1.0, v16.14.0
  766. * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register
  767. * @return Used for disabling hooks
  768. */
  769. createHook: (callbacks: HookCallbacks) => Function;
  770. }
  771. /**
  772. * The `promiseHooks` interface can be used to track promise lifecycle events.
  773. * @since v17.1.0, v16.14.0
  774. */
  775. const promiseHooks: PromiseHooks;
  776. type StartupSnapshotCallbackFn = (args: any) => any;
  777. interface StartupSnapshot {
  778. /**
  779. * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit.
  780. * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization.
  781. * @since v18.6.0, v16.17.0
  782. */
  783. addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
  784. /**
  785. * Add a callback that will be called when the Node.js instance is deserialized from a snapshot.
  786. * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or
  787. * to re-acquire resources that the application needs when the application is restarted from the snapshot.
  788. * @since v18.6.0, v16.17.0
  789. */
  790. addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
  791. /**
  792. * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script.
  793. * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized
  794. * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application.
  795. * @since v18.6.0, v16.17.0
  796. */
  797. setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void;
  798. /**
  799. * Returns true if the Node.js instance is run to build a snapshot.
  800. * @since v18.6.0, v16.17.0
  801. */
  802. isBuildingSnapshot(): boolean;
  803. }
  804. /**
  805. * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots.
  806. *
  807. * ```bash
  808. * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js
  809. * # This launches a process with the snapshot
  810. * $ node --snapshot-blob snapshot.blob
  811. * ```
  812. *
  813. * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects
  814. * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot.
  815. * For example, if the `entry.js` contains the following script:
  816. *
  817. * ```js
  818. * 'use strict';
  819. *
  820. * import fs from 'node:fs';
  821. * import zlib from 'node:zlib';
  822. * import path from 'node:path';
  823. * import assert from 'node:assert';
  824. *
  825. * import v8 from 'node:v8';
  826. *
  827. * class BookShelf {
  828. * storage = new Map();
  829. *
  830. * // Reading a series of files from directory and store them into storage.
  831. * constructor(directory, books) {
  832. * for (const book of books) {
  833. * this.storage.set(book, fs.readFileSync(path.join(directory, book)));
  834. * }
  835. * }
  836. *
  837. * static compressAll(shelf) {
  838. * for (const [ book, content ] of shelf.storage) {
  839. * shelf.storage.set(book, zlib.gzipSync(content));
  840. * }
  841. * }
  842. *
  843. * static decompressAll(shelf) {
  844. * for (const [ book, content ] of shelf.storage) {
  845. * shelf.storage.set(book, zlib.gunzipSync(content));
  846. * }
  847. * }
  848. * }
  849. *
  850. * // __dirname here is where the snapshot script is placed
  851. * // during snapshot building time.
  852. * const shelf = new BookShelf(__dirname, [
  853. * 'book1.en_US.txt',
  854. * 'book1.es_ES.txt',
  855. * 'book2.zh_CN.txt',
  856. * ]);
  857. *
  858. * assert(v8.startupSnapshot.isBuildingSnapshot());
  859. * // On snapshot serialization, compress the books to reduce size.
  860. * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf);
  861. * // On snapshot deserialization, decompress the books.
  862. * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf);
  863. * v8.startupSnapshot.setDeserializeMainFunction((shelf) => {
  864. * // process.env and process.argv are refreshed during snapshot
  865. * // deserialization.
  866. * const lang = process.env.BOOK_LANG || 'en_US';
  867. * const book = process.argv[1];
  868. * const name = `${book}.${lang}.txt`;
  869. * console.log(shelf.storage.get(name));
  870. * }, shelf);
  871. * ```
  872. *
  873. * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process:
  874. *
  875. * ```bash
  876. * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1
  877. * # Prints content of book1.es_ES.txt deserialized from the snapshot.
  878. * ```
  879. *
  880. * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot.
  881. *
  882. * @experimental
  883. * @since v18.6.0, v16.17.0
  884. */
  885. const startupSnapshot: StartupSnapshot;
  886. }
  887. declare module "node:v8" {
  888. export * from "v8";
  889. }