@nomicfoundation/hardhat-utils 4.3.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/src/abi.d.ts +79 -0
  3. package/dist/src/abi.d.ts.map +1 -0
  4. package/dist/src/abi.js +114 -0
  5. package/dist/src/abi.js.map +1 -0
  6. package/dist/src/bytes.d.ts +5 -4
  7. package/dist/src/bytes.d.ts.map +1 -1
  8. package/dist/src/bytes.js +22 -13
  9. package/dist/src/bytes.js.map +1 -1
  10. package/dist/src/errors/abi.d.ts +93 -0
  11. package/dist/src/errors/abi.d.ts.map +1 -0
  12. package/dist/src/errors/abi.js +117 -0
  13. package/dist/src/errors/abi.js.map +1 -0
  14. package/dist/src/fs.d.ts +25 -29
  15. package/dist/src/fs.d.ts.map +1 -1
  16. package/dist/src/fs.js +84 -82
  17. package/dist/src/fs.js.map +1 -1
  18. package/dist/src/internal/abi.d.ts +50 -0
  19. package/dist/src/internal/abi.d.ts.map +1 -0
  20. package/dist/src/internal/abi.js +248 -0
  21. package/dist/src/internal/abi.js.map +1 -0
  22. package/dist/src/internal/bytes.js +3 -3
  23. package/dist/src/internal/bytes.js.map +1 -1
  24. package/dist/src/internal/fs.d.ts +6 -0
  25. package/dist/src/internal/fs.d.ts.map +1 -1
  26. package/dist/src/internal/fs.js +51 -3
  27. package/dist/src/internal/fs.js.map +1 -1
  28. package/dist/src/internal/json.d.ts +48 -0
  29. package/dist/src/internal/json.d.ts.map +1 -0
  30. package/dist/src/internal/json.js +54 -0
  31. package/dist/src/internal/json.js.map +1 -0
  32. package/dist/src/internal/request.d.ts.map +1 -1
  33. package/dist/src/internal/request.js +3 -2
  34. package/dist/src/internal/request.js.map +1 -1
  35. package/package.json +5 -3
  36. package/src/abi.ts +199 -0
  37. package/src/bytes.ts +31 -14
  38. package/src/errors/abi.ts +156 -0
  39. package/src/fs.ts +96 -87
  40. package/src/internal/abi.ts +431 -0
  41. package/src/internal/bytes.ts +4 -4
  42. package/src/internal/fs.ts +66 -3
  43. package/src/internal/json.ts +59 -0
  44. package/src/internal/request.ts +3 -2
package/src/abi.ts ADDED
@@ -0,0 +1,199 @@
1
+ import type { PrefixedHexString } from "./hex.js";
2
+ import type { deployContract as DeployContractT } from "micro-eth-signer/advanced/abi.js";
3
+
4
+ import { ensureError } from "./error.js";
5
+ import {
6
+ AbiEncodingFailedError,
7
+ AbiParametersLengthMismatchError,
8
+ } from "./errors/abi.js";
9
+ import { getPrefixedHexString } from "./hex.js";
10
+ import {
11
+ assertNoDuplicateAbiParameterNames,
12
+ normalizeAbiValue,
13
+ toUnnamedAbiParameters,
14
+ } from "./internal/abi.js";
15
+
16
+ // We don't load micro-eth-signer on startup because it's slow to initialize,
17
+ // and most callers of this module never encode anything.
18
+ let deployContractImpl: typeof DeployContractT | undefined;
19
+
20
+ /**
21
+ * A parameter of an ABI fragment.
22
+ */
23
+ export interface AbiParameter {
24
+ readonly name?: string;
25
+ readonly type: string;
26
+ readonly components?: readonly AbiParameter[];
27
+ }
28
+
29
+ /**
30
+ * An entry of a contract's ABI. Only the fields needed to encode values are
31
+ * modeled.
32
+ */
33
+ export interface AbiFragment {
34
+ readonly type?: string;
35
+ readonly name?: string;
36
+ readonly inputs?: readonly AbiParameter[];
37
+ }
38
+
39
+ /**
40
+ * The signedness and size of a Solidity integer type.
41
+ */
42
+ export interface IntType {
43
+ readonly signed: boolean;
44
+ readonly bits: number;
45
+ }
46
+
47
+ /**
48
+ * The inclusive range of values that a Solidity integer type can hold.
49
+ */
50
+ export interface IntTypeRange {
51
+ readonly min: bigint;
52
+ readonly max: bigint;
53
+ }
54
+
55
+ const INT_TYPE_PATTERN = /^(u?)int([1-9]\d*)?$/;
56
+
57
+ /**
58
+ * Parses a Solidity integer type name, like `uint256` or `int128`, into its
59
+ * signedness and size in bits. As in Solidity, `uint` and `int` are accepted as
60
+ * aliases of the 256-bit types.
61
+ *
62
+ * @param type The type name to parse.
63
+ * @returns The parsed type, or `undefined` if it isn't a Solidity integer type.
64
+ */
65
+ export function parseIntType(type: string): IntType | undefined {
66
+ const match = INT_TYPE_PATTERN.exec(type);
67
+
68
+ if (match === null) {
69
+ return undefined;
70
+ }
71
+
72
+ const bits = match[2] === undefined ? 256 : Number(match[2]);
73
+
74
+ if (bits > 256 || bits % 8 !== 0) {
75
+ return undefined;
76
+ }
77
+
78
+ return { signed: match[1] === "", bits };
79
+ }
80
+
81
+ /**
82
+ * Returns the inclusive range of values that a Solidity integer type can hold.
83
+ *
84
+ * @param intType The integer type, as returned by {@link parseIntType}.
85
+ * @returns The minimum and maximum values of the type.
86
+ */
87
+ export function getIntTypeRange({ signed, bits }: IntType): IntTypeRange {
88
+ if (signed) {
89
+ const bound = 2n ** BigInt(bits - 1);
90
+ return { min: -bound, max: bound - 1n };
91
+ }
92
+
93
+ return { min: 0n, max: 2n ** BigInt(bits) - 1n };
94
+ }
95
+
96
+ /**
97
+ * Returns the parameters of the constructor declared in an ABI.
98
+ *
99
+ * An ABI that declares no constructor yields an empty array, matching the
100
+ * Solidity semantics of an implicit parameterless constructor.
101
+ *
102
+ * @param abi The ABI to read the constructor from.
103
+ * @returns The constructor's parameters.
104
+ */
105
+ export function getAbiConstructorParameters(
106
+ abi: readonly AbiFragment[],
107
+ ): readonly AbiParameter[] {
108
+ return abi.find(({ type }) => type === "constructor")?.inputs ?? [];
109
+ }
110
+
111
+ /**
112
+ * ABI-encodes a list of values, as Solidity encodes a constructor's arguments
113
+ * (i.e. without a function selector).
114
+ *
115
+ * Values are accepted in the same shapes that most Ethereum libraries accept:
116
+ * integers as bigints, safe numbers, or decimal or hex strings; `bytes` as hex
117
+ * strings or `Uint8Array`s; tuples as arrays or as objects keyed by component
118
+ * name; and addresses with or without the "0x" prefix.
119
+ *
120
+ * @param parameters The ABI parameters to encode the values as.
121
+ * @param values The values to encode, in the order of the parameters.
122
+ * @returns The encoded values as a prefixed hex string, or "0x" if there are none.
123
+ * @throws AbiParametersLengthMismatchError If the counts don't match.
124
+ * @throws InvalidAbiValueError If a value can't be encoded as its type.
125
+ * @throws AbiValueOutOfBoundsError If a numeric value is out of its type's range.
126
+ * @throws UnsupportedAbiTypeError If a parameter's type can't be encoded.
127
+ * @throws AbiEncodingFailedError If the encoder fails for any other reason.
128
+ */
129
+ export async function encodeAbiParameters(
130
+ parameters: readonly AbiParameter[],
131
+ values: readonly unknown[],
132
+ ): Promise<PrefixedHexString> {
133
+ if (parameters.length !== values.length) {
134
+ throw new AbiParametersLengthMismatchError(
135
+ parameters.length,
136
+ values.length,
137
+ );
138
+ }
139
+
140
+ // Returning here also keeps micro-eth-signer unloaded.
141
+ if (parameters.length === 0) {
142
+ return "0x";
143
+ }
144
+
145
+ assertNoDuplicateAbiParameterNames(parameters);
146
+
147
+ // The values are normalized sequentially so that, when more than one is
148
+ // invalid, the error reported is always the one of the first.
149
+ const normalizedValues = [];
150
+ for (const [i, parameter] of parameters.entries()) {
151
+ normalizedValues.push(
152
+ await normalizeAbiValue(parameter, values[i], parameter.name ?? `[${i}]`),
153
+ );
154
+ }
155
+
156
+ if (deployContractImpl === undefined) {
157
+ ({ deployContract: deployContractImpl } =
158
+ await import("micro-eth-signer/advanced/abi.js"));
159
+ }
160
+
161
+ // The encoder takes the bare value when there's a single parameter, and a
162
+ // positional array otherwise. The array is positional at every level because
163
+ // toUnnamedAbiParameters drops the names.
164
+ const value =
165
+ parameters.length === 1 ? normalizedValues[0] : normalizedValues;
166
+
167
+ // NOTE: this must not be annotated nor frozen with `as const`. With `type`
168
+ // widened to `string`, micro-eth-signer's generic overload resolves to its
169
+ // untyped form, which is what we want for a dynamically built ABI.
170
+ const abi = [
171
+ { type: "constructor", inputs: toUnnamedAbiParameters(parameters) },
172
+ ];
173
+
174
+ let encoded: string;
175
+ try {
176
+ // deployContract returns `<bytecode><encoded args>`, so we pass no bytecode.
177
+ encoded = deployContractImpl(abi, "0x", value);
178
+ } catch (error) {
179
+ // Reached by types that pass validation but the encoder still refuses,
180
+ // such as `uint256[0][]`, whose zero-size element it treats as a DoS risk.
181
+ ensureError(error);
182
+ throw new AbiEncodingFailedError(error);
183
+ }
184
+
185
+ return getPrefixedHexString(encoded);
186
+ }
187
+
188
+ export {
189
+ AbiEncodingError,
190
+ AbiEncodingFailedError,
191
+ AbiParametersLengthMismatchError,
192
+ AbiValueOutOfBoundsError,
193
+ DuplicateAbiParameterNameError,
194
+ InvalidAbiValueError,
195
+ UnsupportedAbiTypeError,
196
+ isAbiEncodingError,
197
+ type AbiEncodingErrorKind,
198
+ type AnyAbiEncodingError,
199
+ } from "./errors/abi.js";
package/src/bytes.ts CHANGED
@@ -1,6 +1,13 @@
1
+ import { constants as bufferConstants } from "node:buffer";
1
2
  import { Readable } from "node:stream";
2
3
 
4
+ import { InvalidParameterError } from "./common-errors.js";
5
+ import { ensureError } from "./error.js";
3
6
  import { buildLpsTable, parseJsonStream } from "./internal/bytes.js";
7
+ import {
8
+ hasHeapHeadroomFor,
9
+ READ_HEAP_BYTES_PER_JSON_BYTE,
10
+ } from "./internal/json.js";
4
11
 
5
12
  /**
6
13
  * Checks if a value is an instance of Uint8Array.
@@ -110,27 +117,37 @@ export function bytesIncludesUtf8String(
110
117
  /**
111
118
  * Parses UTF-8 encoded JSON bytes into a value.
112
119
  *
113
- * Payloads that fit in a single string are decoded and parsed with
114
- * `JSON.parse`, which is much faster. Payloads too large to be held in a
115
- * single string are parsed as a stream instead, which decodes and parses
116
- * incrementally rather than materializing the whole payload as one string.
120
+ * The bytes are decoded and parsed with `JSON.parse`, which is much faster,
121
+ * when the decoded text fits in a single string and the heap has room for it.
122
+ * Otherwise, they are parsed as a stream, which never holds the whole text as
123
+ * one string. Both give the same result.
117
124
  *
118
125
  * @param bytes The UTF-8 encoded JSON bytes.
119
126
  * @returns The parsed JSON object.
127
+ * @throws InvalidParameterError if the bytes aren't valid UTF-8 encoded JSON.
120
128
  */
121
129
  export async function parseJsonBytes<T>(bytes: Uint8Array): Promise<T> {
122
- let json: string;
123
130
  try {
124
- json = bytesToUtf8String(bytes);
125
- } catch {
126
- // `bytesToUtf8String` decodes non-fatally, so it never throws on malformed
127
- // bytes; its only failure mode is a payload larger than the maximum string
128
- // length the runtime can hold. Stream parsing handles those, as it never
129
- // materializes the whole payload as a single string.
130
- return await parseJsonStream<T>(Readable.from([bytes]));
131
- }
131
+ // Each UTF-8 byte decodes to at most one character, so this also
132
+ // guarantees that the text fits in a string. Everything from the heap
133
+ // check on is synchronous, so no other code can use memory in between.
134
+ if (
135
+ bytes.length > bufferConstants.MAX_STRING_LENGTH ||
136
+ !hasHeapHeadroomFor(bytes.length * READ_HEAP_BYTES_PER_JSON_BYTE)
137
+ ) {
138
+ return await parseJsonStream<T>(Readable.from([bytes]));
139
+ }
132
140
 
133
- return JSON.parse(json);
141
+ // Like the stream parser, this skips a leading BOM and rejects invalid
142
+ // UTF-8, so both paths behave the same.
143
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
144
+ } catch (e) {
145
+ ensureError(e);
146
+ throw new InvalidParameterError(
147
+ "The bytes are not valid UTF-8 encoded JSON",
148
+ e,
149
+ );
150
+ }
134
151
  }
135
152
 
136
153
  export { bytesToBigInt, bytesToNumber, numberToBytes } from "./number.js";
@@ -0,0 +1,156 @@
1
+ import { CustomError } from "../error.js";
2
+
3
+ /**
4
+ * Discriminates the errors that ABI encoding can throw.
5
+ */
6
+ export type AbiEncodingErrorKind =
7
+ | "parameters-length-mismatch"
8
+ | "invalid-value"
9
+ | "value-out-of-bounds"
10
+ | "unsupported-type"
11
+ | "duplicate-parameter-name"
12
+ | "encoding-failed";
13
+
14
+ /**
15
+ * Base class of every error thrown while ABI-encoding values.
16
+ *
17
+ * Consumers should discriminate with `isAbiEncodingError` rather than
18
+ * `instanceof`, so that the checks keep working if more than one copy of this
19
+ * package ends up installed.
20
+ */
21
+ export abstract class AbiEncodingError extends CustomError {
22
+ public abstract readonly kind: AbiEncodingErrorKind;
23
+ }
24
+
25
+ /**
26
+ * Thrown when the number of values to encode doesn't match the number of
27
+ * parameters.
28
+ */
29
+ export class AbiParametersLengthMismatchError extends AbiEncodingError {
30
+ public readonly kind: "parameters-length-mismatch" =
31
+ "parameters-length-mismatch";
32
+
33
+ constructor(
34
+ public readonly expectedLength: number,
35
+ public readonly providedLength: number,
36
+ ) {
37
+ super(
38
+ `Expected ${expectedLength} values to encode, but ${providedLength} were provided.`,
39
+ );
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Thrown when a value can't be encoded as its parameter's Solidity type.
45
+ */
46
+ export class InvalidAbiValueError extends AbiEncodingError {
47
+ public readonly kind: "invalid-value" = "invalid-value";
48
+
49
+ constructor(
50
+ public readonly path: string,
51
+ public readonly solidityType: string,
52
+ public readonly value: unknown,
53
+ public readonly reason: string,
54
+ ) {
55
+ super(
56
+ `The value provided for the parameter "${path}" of type "${solidityType}" cannot be encoded. Reason: ${reason}.`,
57
+ );
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Thrown when a numeric value is outside the range of its Solidity type.
63
+ */
64
+ export class AbiValueOutOfBoundsError extends AbiEncodingError {
65
+ public readonly kind: "value-out-of-bounds" = "value-out-of-bounds";
66
+
67
+ constructor(
68
+ public readonly path: string,
69
+ public readonly solidityType: string,
70
+ public readonly value: unknown,
71
+ public readonly min: bigint,
72
+ public readonly max: bigint,
73
+ ) {
74
+ super(
75
+ `The value provided for the parameter "${path}" is out of bounds for the type "${solidityType}". Expected a value between ${min} and ${max}.`,
76
+ );
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Thrown when a parameter's Solidity type can't be encoded at all.
82
+ */
83
+ export class UnsupportedAbiTypeError extends AbiEncodingError {
84
+ public readonly kind: "unsupported-type" = "unsupported-type";
85
+
86
+ constructor(
87
+ public readonly path: string,
88
+ public readonly solidityType: string,
89
+ ) {
90
+ super(
91
+ `The type "${solidityType}" of the parameter "${path}" is not supported.`,
92
+ );
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Thrown when two parameters, or two components of the same tuple, share a
98
+ * name.
99
+ *
100
+ * Only a hand-written ABI can carry duplicate names; solc never emits one. The
101
+ * encoder's own guard covers named parameters only, and names are stripped
102
+ * before it runs, so it never sees them.
103
+ */
104
+ export class DuplicateAbiParameterNameError extends AbiEncodingError {
105
+ public readonly kind: "duplicate-parameter-name" = "duplicate-parameter-name";
106
+
107
+ constructor(
108
+ // undefined when the duplicate is between top-level parameters
109
+ public readonly path: string | undefined,
110
+ public readonly duplicatedName: string,
111
+ ) {
112
+ super(
113
+ path === undefined
114
+ ? `Two or more parameters are named "${duplicatedName}".`
115
+ : `Two or more components of the parameter "${path}" are named "${duplicatedName}".`,
116
+ );
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Thrown when the encoder refuses values that already passed validation.
122
+ */
123
+ export class AbiEncodingFailedError extends AbiEncodingError {
124
+ public readonly kind: "encoding-failed" = "encoding-failed";
125
+
126
+ constructor(cause: Error) {
127
+ // The encoder's messages don't end with a period, so one is added to keep
128
+ // this message punctuated like the rest.
129
+ super(`The values could not be ABI-encoded: ${cause.message}.`, cause);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * The union of every error that ABI encoding can throw.
135
+ */
136
+ export type AnyAbiEncodingError =
137
+ | AbiParametersLengthMismatchError
138
+ | InvalidAbiValueError
139
+ | AbiValueOutOfBoundsError
140
+ | UnsupportedAbiTypeError
141
+ | DuplicateAbiParameterNameError
142
+ | AbiEncodingFailedError;
143
+
144
+ /**
145
+ * Checks whether a value is the ABI encoding error of the given kind.
146
+ *
147
+ * @param error The value to check.
148
+ * @param kind The kind of error to check for.
149
+ * @returns True if the value is an ABI encoding error of that kind.
150
+ */
151
+ export function isAbiEncodingError<KindT extends AbiEncodingErrorKind>(
152
+ error: unknown,
153
+ kind: KindT,
154
+ ): error is Extract<AnyAbiEncodingError, { kind: KindT }> {
155
+ return error instanceof Error && "kind" in error && error.kind === kind;
156
+ }
package/src/fs.ts CHANGED
@@ -1,11 +1,11 @@
1
- import type * as JsonStreamStringify from "json-stream-stringify";
2
1
  import type { FileHandle } from "node:fs/promises";
3
2
 
3
+ import { constants as bufferConstants } from "node:buffer";
4
4
  import fsPromises from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import path from "node:path";
7
- import { pipeline } from "node:stream/promises";
8
7
 
8
+ import { parseJsonBytes } from "./bytes.js";
9
9
  import { ensureError, ensureNodeErrnoExceptionError } from "./error.js";
10
10
  import {
11
11
  FileNotFoundError,
@@ -21,11 +21,20 @@ import { parseJsonStream } from "./internal/bytes.js";
21
21
  import {
22
22
  collectAllDirectoriesMatching,
23
23
  collectAllFilesMatching,
24
+ streamJsonToFile,
24
25
  } from "./internal/fs.js";
25
-
26
- // We don't load json-stream-stringify on startup because it's only
27
- // used by writeJsonFileAsStream for very large JSON objects.
28
- let jsonStreamStringify: typeof JsonStreamStringify | undefined;
26
+ import {
27
+ hasHeapHeadroomFor,
28
+ READ_HEAP_BYTES_PER_JSON_BYTE,
29
+ WRITE_HEAP_BYTES_PER_JSON_BYTE,
30
+ } from "./internal/json.js";
31
+ import { AsyncMutex } from "./synchronization.js";
32
+
33
+ // Lets only one call of writeLargeJsonFile use JSON.stringify at a time, so
34
+ // that their strings don't use up each other's heap headroom.
35
+ // NOTE: Created on first use: synchronization.ts imports this file, so
36
+ // AsyncMutex may not be initialized yet while this file is first loading.
37
+ let bufferedWriteMutex: AsyncMutex | undefined;
29
38
 
30
39
  const AMBIGUOUS_CASING_DIR_ENTRY = Symbol("ambiguous");
31
40
 
@@ -343,25 +352,6 @@ export async function getAllDirectoriesMatching(
343
352
  return results;
344
353
  }
345
354
 
346
- /**
347
- * Determines the true case path of a given relative path from a specified
348
- * directory, without resolving symbolic links, and returns it.
349
- *
350
- * @param from The absolute path of the directory to start the search from.
351
- * @param relativePath The relative path to get the true case of.
352
- * @returns The true case of the relative path.
353
- * @throws FileNotFoundError if the starting directory or the relative path doesn't exist.
354
- * @throws NotADirectoryError if the starting directory is not a directory.
355
- * @throws FileSystemAccessError for any other error.
356
- * @deprecated Use {@link TrueCasePathResolver} instead.
357
- */
358
- export async function getFileTrueCase(
359
- from: string,
360
- relativePath: string,
361
- ): Promise<string> {
362
- return await new TrueCasePathResolver().getFileTrueCase(from, relativePath);
363
- }
364
-
365
355
  /**
366
356
  * Checks if a given path is a directory.
367
357
  *
@@ -386,26 +376,10 @@ export async function isDirectory(absolutePath: string): Promise<boolean> {
386
376
  /**
387
377
  * Reads a JSON file and parses it. The encoding used is "utf8".
388
378
  *
389
- * @param absolutePathToFile The path to the file.
390
- * @returns The parsed JSON object.
391
- * @throws FileNotFoundError if the file doesn't exist.
392
- * @throws InvalidFileFormatError if the file is not a valid JSON file.
393
- * @throws IsDirectoryError if the path is a directory instead of a file.
394
- * @throws FileSystemAccessError for any other error.
395
- */
396
- export async function readJsonFile<T>(absolutePathToFile: string): Promise<T> {
397
- const content = await readUtf8File(absolutePathToFile);
398
- try {
399
- return JSON.parse(content.toString());
400
- } catch (e) {
401
- ensureError(e);
402
- throw new InvalidFileFormatError(absolutePathToFile, e);
403
- }
404
- }
405
-
406
- /**
407
- * Reads a JSON file as a stream and parses it. The encoding used is "utf8".
408
- * This function should be used when parsing very large JSON files.
379
+ * Files of any size are supported. The file is parsed with `JSON.parse`,
380
+ * which is much faster, when its text fits in a single string and the heap has
381
+ * room for it. Otherwise, it's parsed as a stream, which never holds the whole
382
+ * text as one string. Both give the same result.
409
383
  *
410
384
  * @param absolutePathToFile The path to the file.
411
385
  * @returns The parsed JSON object.
@@ -414,20 +388,37 @@ export async function readJsonFile<T>(absolutePathToFile: string): Promise<T> {
414
388
  * @throws IsDirectoryError if the path is a directory instead of a file.
415
389
  * @throws FileSystemAccessError for any other error.
416
390
  */
417
- export async function readJsonFileAsStream<T>(
418
- absolutePathToFile: string,
419
- ): Promise<T> {
391
+ export async function readJsonFile<T>(absolutePathToFile: string): Promise<T> {
420
392
  let fileHandle: FileHandle | undefined;
421
393
 
422
394
  try {
423
395
  fileHandle = await fsPromises.open(absolutePathToFile, "r");
424
396
 
425
- return await parseJsonStream<T>(fileHandle.createReadStream());
397
+ // Each UTF-8 byte decodes to at most one character, so the file's size
398
+ // tells us whether its text could fit in a string. If it can't, or the
399
+ // heap has no room for it right now, we stream it from disk instead of
400
+ // reading it all into memory.
401
+ const { size } = await fileHandle.stat();
402
+ if (
403
+ size > bufferConstants.MAX_STRING_LENGTH ||
404
+ !hasHeapHeadroomFor(size * READ_HEAP_BYTES_PER_JSON_BYTE)
405
+ ) {
406
+ return await parseJsonStream<T>(fileHandle.createReadStream());
407
+ }
408
+
409
+ // The bytes are stored outside of the heap. parseJsonBytes checks the heap
410
+ // again, as other code may have used it while we were reading.
411
+ return await parseJsonBytes<T>(await fileHandle.readFile());
426
412
  } catch (e) {
427
413
  ensureError(e);
428
414
 
429
415
  // If the code is defined, we assume the error to be related to the file system
430
416
  if ("code" in e) {
417
+ // Except for invalid UTF-8, which is a problem with the file's contents
418
+ if (e.code === "ERR_ENCODING_INVALID_ENCODED_DATA") {
419
+ throw new InvalidFileFormatError(absolutePathToFile, e);
420
+ }
421
+
431
422
  if (e.code === "ENOENT") {
432
423
  throw new FileNotFoundError(absolutePathToFile, e);
433
424
  }
@@ -438,7 +429,7 @@ export async function readJsonFileAsStream<T>(
438
429
 
439
430
  // If the code is defined, we assume the error to be related to the file system
440
431
  if (e.code !== undefined) {
441
- throw new FileSystemAccessError(absolutePathToFile, e);
432
+ throw new FileSystemAccessError(e.message, e);
442
433
  }
443
434
  }
444
435
 
@@ -475,59 +466,77 @@ export async function writeJsonFile<T>(
475
466
  }
476
467
 
477
468
  /**
478
- * Writes an object to a JSON file as stream. The encoding used is "utf8" and the file is overwritten.
479
- * If part of the path doesn't exist, it will be created.
480
- * This function should be used when stringifying very large JSON objects.
469
+ * Writes an object to a JSON file, supporting objects whose JSON is too large
470
+ * to be held in a single string. The JSON is compact (not indented), the
471
+ * encoding used is "utf8", and the file is overwritten. If part of the path
472
+ * doesn't exist, it will be created.
473
+ *
474
+ * Use this function for objects whose JSON can be very large, like solc's
475
+ * output, and {@link writeJsonFile} for everything else.
476
+ *
477
+ * The object is serialized with `JSON.stringify`, which is much faster, when
478
+ * the heap has room for the longest string it could build. Otherwise, or if
479
+ * its JSON doesn't fit in a single string, it's serialized as a stream, which
480
+ * never holds the whole JSON as one string. Only one call uses
481
+ * `JSON.stringify` at a time: concurrent calls take turns.
482
+ *
483
+ * Both write the same JSON, except for objects that contain a BigInt, a
484
+ * Promise, or a `toJSON` method that throws. `JSON.stringify` throws a
485
+ * `JsonSerializationError` for a BigInt or a throwing `toJSON`, and writes a
486
+ * Promise as `{}`. The stream writes a BigInt as a plain number, writes a
487
+ * Promise's resolved value, and crashes the process if a `toJSON` throws.
481
488
  *
482
489
  * @param absolutePathToFile The path to the file. If the file exists, it will be overwritten.
483
490
  * @param object The object to write.
484
491
  * @throws JsonSerializationError if the object can't be serialized to JSON.
485
492
  * @throws FileSystemAccessError for any other error.
486
493
  */
487
- export async function writeJsonFileAsStream<T>(
494
+ export async function writeLargeJsonFile<T>(
488
495
  absolutePathToFile: string,
489
496
  object: T,
490
497
  ): Promise<void> {
491
- const dirPath = path.dirname(absolutePathToFile);
492
- const dirExists = await exists(dirPath);
493
- if (!dirExists) {
494
- await mkdir(dirPath);
495
- }
496
-
497
- let fileHandle: FileHandle | undefined;
498
-
499
- try {
500
- fileHandle = await fsPromises.open(absolutePathToFile, "w");
498
+ bufferedWriteMutex ??= new AsyncMutex();
501
499
 
502
- if (jsonStreamStringify === undefined) {
503
- jsonStreamStringify = await import("json-stream-stringify");
500
+ const written = await bufferedWriteMutex.exclusiveRun(async () => {
501
+ // We can't know the JSON's length before building it, so we require room
502
+ // for the longest string V8 can build. JSON.stringify throws a RangeError
503
+ // instead of going past it, so with this much heap free, it can't run out.
504
+ if (
505
+ !hasHeapHeadroomFor(
506
+ bufferConstants.MAX_STRING_LENGTH * WRITE_HEAP_BYTES_PER_JSON_BYTE,
507
+ )
508
+ ) {
509
+ return false;
504
510
  }
505
511
 
506
- const jsonStream = new jsonStreamStringify.JsonStreamStringify(object);
507
- const fileWriteStream = fileHandle.createWriteStream();
512
+ let json: string;
513
+ try {
514
+ json = JSON.stringify(object);
515
+ } catch (e) {
516
+ ensureError(e);
508
517
 
509
- await pipeline(jsonStream, fileWriteStream);
510
- } catch (e) {
511
- ensureError(e);
512
- // if the directory was created, we should remove it
513
- if (dirExists === false) {
514
- try {
515
- await remove(dirPath);
516
- // we don't want to override the original error
517
- } catch (_error) {}
518
- }
518
+ // The JSON is too long for a string, or the object is nested too deeply
519
+ // for JSON.stringify. Streaming handles both.
520
+ if (e instanceof RangeError) {
521
+ return false;
522
+ }
519
523
 
520
- // If the code is defined, we assume the error to be related to the file system
521
- if ("code" in e && e.code !== undefined) {
522
- throw new FileSystemAccessError(e.message, e);
524
+ // Anything else isn't about size, so streaming wouldn't help:
525
+ // - A circular object (TypeError): streaming detects it too.
526
+ // - A BigInt (TypeError): streaming writes it as a plain number, which
527
+ // is read back as a rounded number if it's too large. Failing is safer.
528
+ // - An error thrown by a toJSON method: streaming can't report it, and
529
+ // crashes the process instead.
530
+ throw new JsonSerializationError(absolutePathToFile, e);
523
531
  }
524
532
 
525
- // Otherwise, we assume the error to be related to the file formatting
526
- throw new JsonSerializationError(absolutePathToFile, e);
527
- } finally {
528
- // NOTE: Historically, not closing the file handle caused issues on Windows,
529
- // for example, when trying to move the file previously written to by this function
530
- await fileHandle?.close();
533
+ await writeUtf8File(absolutePathToFile, json);
534
+ return true;
535
+ });
536
+
537
+ if (!written) {
538
+ // Streaming uses little memory, so it doesn't need to take turns.
539
+ await streamJsonToFile(absolutePathToFile, object);
531
540
  }
532
541
  }
533
542