@nomicfoundation/hardhat-utils 4.4.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,22 @@
1
+ import type * as JsonStreamStringify from "json-stream-stringify";
1
2
  import type { Dirent } from "node:fs";
3
+ import type { FileHandle } from "node:fs/promises";
2
4
 
3
5
  import fsPromises from "node:fs/promises";
4
6
  import path from "node:path";
7
+ import { pipeline } from "node:stream/promises";
5
8
 
6
- import { ensureNodeErrnoExceptionError } from "../error.js";
7
- import { FileSystemAccessError, NotADirectoryError } from "../errors/fs.js";
8
- import { isDirectory } from "../fs.js";
9
+ import { ensureError, ensureNodeErrnoExceptionError } from "../error.js";
10
+ import {
11
+ FileSystemAccessError,
12
+ JsonSerializationError,
13
+ NotADirectoryError,
14
+ } from "../errors/fs.js";
15
+ import { exists, isDirectory, mkdir, remove } from "../fs.js";
16
+
17
+ // We don't load json-stream-stringify on startup because it's only used by
18
+ // writeLargeJsonFile when it can't use JSON.stringify.
19
+ let jsonStreamStringify: typeof JsonStreamStringify | undefined;
9
20
 
10
21
  /**
11
22
  * Like `readdirOrEmpty`, but returns `Dirent` entries to know if an entry is a
@@ -125,3 +136,55 @@ export async function collectAllDirectoriesMatching(
125
136
  }),
126
137
  );
127
138
  }
139
+
140
+ /**
141
+ * Writes an object to a JSON file as a stream, which never holds the whole
142
+ * JSON as a single string. It's used by `writeLargeJsonFile` when it can't use
143
+ * `JSON.stringify`.
144
+ */
145
+ export async function streamJsonToFile(
146
+ absolutePathToFile: string,
147
+ object: unknown,
148
+ ): Promise<void> {
149
+ const dirPath = path.dirname(absolutePathToFile);
150
+ const dirExists = await exists(dirPath);
151
+ if (!dirExists) {
152
+ await mkdir(dirPath);
153
+ }
154
+
155
+ let fileHandle: FileHandle | undefined;
156
+
157
+ try {
158
+ fileHandle = await fsPromises.open(absolutePathToFile, "w");
159
+
160
+ if (jsonStreamStringify === undefined) {
161
+ jsonStreamStringify = await import("json-stream-stringify");
162
+ }
163
+
164
+ const jsonStream = new jsonStreamStringify.JsonStreamStringify(object);
165
+ const fileWriteStream = fileHandle.createWriteStream();
166
+
167
+ await pipeline(jsonStream, fileWriteStream);
168
+ } catch (e) {
169
+ ensureError(e);
170
+ // if the directory was created, we should remove it
171
+ if (dirExists === false) {
172
+ try {
173
+ await remove(dirPath);
174
+ // we don't want to override the original error
175
+ } catch (_error) {}
176
+ }
177
+
178
+ // If the code is defined, we assume the error to be related to the file system
179
+ if ("code" in e && e.code !== undefined) {
180
+ throw new FileSystemAccessError(e.message, e);
181
+ }
182
+
183
+ // Otherwise, we assume the error to be related to the file formatting
184
+ throw new JsonSerializationError(absolutePathToFile, e);
185
+ } finally {
186
+ // NOTE: Historically, not closing the file handle caused issues on Windows,
187
+ // for example, when trying to move the file previously written to by this function
188
+ await fileHandle?.close();
189
+ }
190
+ }
@@ -0,0 +1,59 @@
1
+ // NOTE: We use the default import so that tests can mock getHeapStatistics.
2
+ import v8 from "node:v8";
3
+
4
+ /**
5
+ * The heap needed per byte of JSON to parse it with `JSON.parse`.
6
+ *
7
+ * At its peak, `JSON.parse` holds both the whole text, as a single string, and
8
+ * the objects it builds:
9
+ * - V8 stores a string with 1 byte per character only if every character is
10
+ * in Latin-1, and otherwise with 2. Real-world JSON rarely qualifies: solc's
11
+ * output, for example, usually includes NatSpec comments, which can use
12
+ * characters like `’`, `→` or `—`. Each UTF-8 byte decodes to at most one
13
+ * character, so the string takes at most 2 bytes per byte of JSON.
14
+ * - The objects add about 1.6 bytes per byte of JSON.
15
+ *
16
+ * Measured on real solc output (19 and 95 MB) as the smallest
17
+ * `--max-old-space-size` the parse succeeds with, the peak was about 3.6 bytes
18
+ * per byte, the worst of Node 22, 24 and 26. Rounded up.
19
+ */
20
+ export const READ_HEAP_BYTES_PER_JSON_BYTE = 4;
21
+
22
+ /**
23
+ * The heap needed per byte of JSON to serialize it with `JSON.stringify`.
24
+ *
25
+ * The objects already exist, so it's just the output string, at 2 bytes per
26
+ * character (see above). Measured the same way on Node 22, 24 and 26, a
27
+ * ~400M-character output needed exactly the string's size, with no extra
28
+ * peak.
29
+ */
30
+ export const WRITE_HEAP_BYTES_PER_JSON_BYTE = 2;
31
+
32
+ /**
33
+ * Extra heap we require on top of our own allocation, for everything else that
34
+ * needs it while that allocation is alive, like garbage collection and the
35
+ * rest of the program, and to absorb small errors in the estimates above.
36
+ *
37
+ * It isn't measured: it's a cautious round number, small next to Node's
38
+ * default heap limits (about 2 to 4 GiB, depending on the machine's memory).
39
+ */
40
+ export const HEAP_MARGIN_BYTES: number = 256 * 1024 * 1024;
41
+
42
+ /**
43
+ * Checks whether the heap can grow by `bytes`, plus a safety margin, before
44
+ * reaching its limit.
45
+ *
46
+ * Running out of heap crashes the process, and can't be caught, so this must
47
+ * be called right before the allocation. At each `await` in between, other
48
+ * code can run and use memory.
49
+ *
50
+ * @param bytes The number of bytes about to be allocated in the heap.
51
+ * @returns `true` if there's enough room for them.
52
+ */
53
+ export function hasHeapHeadroomFor(bytes: number): boolean {
54
+ // `total_available_size` counts garbage that hasn't been collected yet as
55
+ // used, so this errs toward `false`, which is the safe direction.
56
+ return (
57
+ bytes + HEAP_MARGIN_BYTES <= v8.getHeapStatistics().total_available_size
58
+ );
59
+ }
@@ -3,7 +3,6 @@ import type EventEmitter from "node:events";
3
3
  import type * as UndiciT from "undici";
4
4
 
5
5
  import crypto from "node:crypto";
6
- import { STATUS_CODES } from "node:http";
7
6
  import path from "node:path";
8
7
 
9
8
  import { mkdir } from "../fs.js";
@@ -376,7 +375,9 @@ function describeResponseError(e: Error): void {
376
375
  return;
377
376
  }
378
377
 
379
- const reason = STATUS_CODES[statusCode];
378
+ // Importing `node:http` loads Node's whole HTTP stack, so we defer
379
+ // using `process.getBuiltinModule` as a dynamic load.
380
+ const reason = process.getBuiltinModule("node:http").STATUS_CODES[statusCode];
380
381
 
381
382
  e.message = `Response status code ${statusCode}${
382
383
  reason !== undefined ? `: ${reason}` : ""