@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.
- package/CHANGELOG.md +26 -0
- package/dist/src/abi.d.ts +79 -0
- package/dist/src/abi.d.ts.map +1 -0
- package/dist/src/abi.js +114 -0
- package/dist/src/abi.js.map +1 -0
- package/dist/src/bytes.d.ts +5 -4
- package/dist/src/bytes.d.ts.map +1 -1
- package/dist/src/bytes.js +22 -13
- package/dist/src/bytes.js.map +1 -1
- package/dist/src/errors/abi.d.ts +93 -0
- package/dist/src/errors/abi.d.ts.map +1 -0
- package/dist/src/errors/abi.js +117 -0
- package/dist/src/errors/abi.js.map +1 -0
- package/dist/src/fs.d.ts +25 -29
- package/dist/src/fs.d.ts.map +1 -1
- package/dist/src/fs.js +84 -82
- package/dist/src/fs.js.map +1 -1
- package/dist/src/internal/abi.d.ts +50 -0
- package/dist/src/internal/abi.d.ts.map +1 -0
- package/dist/src/internal/abi.js +248 -0
- package/dist/src/internal/abi.js.map +1 -0
- package/dist/src/internal/bytes.js +3 -3
- package/dist/src/internal/bytes.js.map +1 -1
- package/dist/src/internal/fs.d.ts +6 -0
- package/dist/src/internal/fs.d.ts.map +1 -1
- package/dist/src/internal/fs.js +51 -3
- package/dist/src/internal/fs.js.map +1 -1
- package/dist/src/internal/json.d.ts +48 -0
- package/dist/src/internal/json.d.ts.map +1 -0
- package/dist/src/internal/json.js +54 -0
- package/dist/src/internal/json.js.map +1 -0
- package/dist/src/internal/request.d.ts.map +1 -1
- package/dist/src/internal/request.js +3 -2
- package/dist/src/internal/request.js.map +1 -1
- package/package.json +5 -3
- package/src/abi.ts +199 -0
- package/src/bytes.ts +31 -14
- package/src/errors/abi.ts +156 -0
- package/src/fs.ts +96 -87
- package/src/internal/abi.ts +431 -0
- package/src/internal/bytes.ts +4 -4
- package/src/internal/fs.ts +66 -3
- package/src/internal/json.ts +59 -0
- package/src/internal/request.ts +3 -2
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
import type { AbiParameter } from "../abi.js";
|
|
2
|
+
|
|
3
|
+
import { getIntTypeRange, parseIntType } from "../abi.js";
|
|
4
|
+
import {
|
|
5
|
+
AbiValueOutOfBoundsError,
|
|
6
|
+
DuplicateAbiParameterNameError,
|
|
7
|
+
InvalidAbiValueError,
|
|
8
|
+
UnsupportedAbiTypeError,
|
|
9
|
+
} from "../errors/abi.js";
|
|
10
|
+
import { isAddress, isValidChecksumAddress } from "../eth.js";
|
|
11
|
+
import {
|
|
12
|
+
getPrefixedHexString,
|
|
13
|
+
getUnprefixedHexString,
|
|
14
|
+
hexStringToBytes,
|
|
15
|
+
isHexString,
|
|
16
|
+
isPrefixedHexString,
|
|
17
|
+
} from "../hex.js";
|
|
18
|
+
import { isObject } from "../lang.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A value in the shape that the encoder expects. Aggregates are always
|
|
22
|
+
* positional, because we strip the parameter names before encoding.
|
|
23
|
+
*/
|
|
24
|
+
export type NormalizedAbiValue =
|
|
25
|
+
bigint | boolean | string | Uint8Array | NormalizedAbiValue[];
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* An ABI parameter with every name removed, recursively.
|
|
29
|
+
*/
|
|
30
|
+
export interface UnnamedAbiParameter {
|
|
31
|
+
readonly type: string;
|
|
32
|
+
readonly components?: readonly UnnamedAbiParameter[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// In Solidity the rightmost suffix is the outermost array, so `uint256[2][]` is
|
|
36
|
+
// a dynamic array of `uint256[2]`. The greedy `.+` matches that last suffix.
|
|
37
|
+
const ARRAY_REGEX = /^(.+)(\[(\d+)?\])$/;
|
|
38
|
+
const BYTES_N_REGEX = /^bytes([0-9]{1,2})$/;
|
|
39
|
+
const DECIMAL_REGEX = /^\d+$/;
|
|
40
|
+
const HEX_REGEX = /^0x[0-9a-f]+$/i;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Throws if two of the given parameters share a name.
|
|
44
|
+
*
|
|
45
|
+
* This is checked against the parameter list rather than the value, so that the
|
|
46
|
+
* array and object input shapes fail the same way.
|
|
47
|
+
*
|
|
48
|
+
* @param parameters The parameters to check.
|
|
49
|
+
* @param path The path of their container, or undefined at the top level.
|
|
50
|
+
* @throws DuplicateAbiParameterNameError If a name is repeated.
|
|
51
|
+
*/
|
|
52
|
+
export function assertNoDuplicateAbiParameterNames(
|
|
53
|
+
parameters: readonly AbiParameter[],
|
|
54
|
+
path?: string,
|
|
55
|
+
): void {
|
|
56
|
+
const seen = new Set<string>();
|
|
57
|
+
for (const { name } of parameters) {
|
|
58
|
+
if (name === undefined || name === "") {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (seen.has(name)) {
|
|
63
|
+
throw new DuplicateAbiParameterNameError(path, name);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
seen.add(name);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Removes the names of a list of ABI parameters, recursively.
|
|
72
|
+
*
|
|
73
|
+
* The encoder derives the shape of the value it expects from whether the
|
|
74
|
+
* parameters are named: named ones take an object keyed by name, unnamed ones
|
|
75
|
+
* take a positional array. Dropping the names makes every aggregate positional,
|
|
76
|
+
* at every nesting level.
|
|
77
|
+
*
|
|
78
|
+
* @param parameters The parameters to strip.
|
|
79
|
+
* @returns The same parameters, without their names.
|
|
80
|
+
*/
|
|
81
|
+
export function toUnnamedAbiParameters(
|
|
82
|
+
parameters: readonly AbiParameter[],
|
|
83
|
+
): UnnamedAbiParameter[] {
|
|
84
|
+
return parameters.map(({ type, components }) =>
|
|
85
|
+
components === undefined
|
|
86
|
+
? { type }
|
|
87
|
+
: { type, components: toUnnamedAbiParameters(components) },
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Converts a value into the shape that the encoder expects for a parameter,
|
|
93
|
+
* validating it against the parameter's Solidity type.
|
|
94
|
+
*
|
|
95
|
+
* @param parameter The ABI parameter to normalize the value for.
|
|
96
|
+
* @param value The value to normalize.
|
|
97
|
+
* @param path The path of the parameter, used to report errors.
|
|
98
|
+
* @returns The normalized value.
|
|
99
|
+
* @throws InvalidAbiValueError If the value can't be encoded as the type.
|
|
100
|
+
* @throws AbiValueOutOfBoundsError If a numeric value is out of the type's range.
|
|
101
|
+
* @throws UnsupportedAbiTypeError If the type itself can't be encoded.
|
|
102
|
+
*/
|
|
103
|
+
export async function normalizeAbiValue(
|
|
104
|
+
parameter: AbiParameter,
|
|
105
|
+
value: unknown,
|
|
106
|
+
path: string,
|
|
107
|
+
): Promise<NormalizedAbiValue> {
|
|
108
|
+
const { type } = parameter;
|
|
109
|
+
|
|
110
|
+
// Arrays must be checked first, as the check is recursive.
|
|
111
|
+
const arrayMatch = ARRAY_REGEX.exec(type);
|
|
112
|
+
if (arrayMatch !== null) {
|
|
113
|
+
return await normalizeArray(parameter, value, path, arrayMatch);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (type === "tuple") {
|
|
117
|
+
return await normalizeTuple(parameter, value, path);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (type === "address") {
|
|
121
|
+
return await normalizeAddress(value, path);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (type === "bool") {
|
|
125
|
+
return normalizeBool(value, path);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (type === "string") {
|
|
129
|
+
if (typeof value !== "string") {
|
|
130
|
+
throw new InvalidAbiValueError(path, type, value, "invalid string value");
|
|
131
|
+
}
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (type === "bytes") {
|
|
136
|
+
return normalizeBytes(value, path, type, undefined);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const bytesNMatch = BYTES_N_REGEX.exec(type);
|
|
140
|
+
if (bytesNMatch !== null) {
|
|
141
|
+
const length = Number(bytesNMatch[1]);
|
|
142
|
+
if (length < 1 || length > 32) {
|
|
143
|
+
throw new UnsupportedAbiTypeError(path, type);
|
|
144
|
+
}
|
|
145
|
+
return normalizeBytes(value, path, type, length);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const intType = parseIntType(type);
|
|
149
|
+
if (intType !== undefined) {
|
|
150
|
+
return normalizeInt(value, path, type, intType);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
throw new UnsupportedAbiTypeError(path, type);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function normalizeArray(
|
|
157
|
+
parameter: AbiParameter,
|
|
158
|
+
value: unknown,
|
|
159
|
+
path: string,
|
|
160
|
+
arrayMatch: RegExpExecArray,
|
|
161
|
+
): Promise<NormalizedAbiValue[]> {
|
|
162
|
+
const { type } = parameter;
|
|
163
|
+
const elementType = arrayMatch[1];
|
|
164
|
+
const fixedLength = arrayMatch[3];
|
|
165
|
+
|
|
166
|
+
if (!Array.isArray(value)) {
|
|
167
|
+
throw new InvalidAbiValueError(
|
|
168
|
+
path,
|
|
169
|
+
type,
|
|
170
|
+
value,
|
|
171
|
+
"invalid array value, expected a JS array",
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (fixedLength !== undefined && value.length !== Number(fixedLength)) {
|
|
176
|
+
throw new InvalidAbiValueError(
|
|
177
|
+
path,
|
|
178
|
+
type,
|
|
179
|
+
value,
|
|
180
|
+
`invalid array length, expected ${fixedLength} elements but got ${value.length}`,
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const elementParameter = { ...parameter, type: elementType };
|
|
185
|
+
const normalized: NormalizedAbiValue[] = [];
|
|
186
|
+
for (const [i, element] of value.entries()) {
|
|
187
|
+
normalized.push(
|
|
188
|
+
await normalizeAbiValue(elementParameter, element, `${path}[${i}]`),
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return normalized;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function normalizeTuple(
|
|
196
|
+
parameter: AbiParameter,
|
|
197
|
+
value: unknown,
|
|
198
|
+
path: string,
|
|
199
|
+
): Promise<NormalizedAbiValue[]> {
|
|
200
|
+
const { type, components } = parameter;
|
|
201
|
+
|
|
202
|
+
// The encoder rejects zero-sized tuples, as arrays of them can be used to
|
|
203
|
+
// DoS the decoder.
|
|
204
|
+
if (components === undefined || components.length === 0) {
|
|
205
|
+
throw new UnsupportedAbiTypeError(path, type);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
assertNoDuplicateAbiParameterNames(components, path);
|
|
209
|
+
|
|
210
|
+
if (Array.isArray(value)) {
|
|
211
|
+
if (value.length !== components.length) {
|
|
212
|
+
throw new InvalidAbiValueError(
|
|
213
|
+
path,
|
|
214
|
+
type,
|
|
215
|
+
value,
|
|
216
|
+
`invalid tuple length, expected ${components.length} components but got ${value.length}`,
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const normalized: NormalizedAbiValue[] = [];
|
|
221
|
+
for (const [i, component] of components.entries()) {
|
|
222
|
+
normalized.push(
|
|
223
|
+
await normalizeAbiValue(
|
|
224
|
+
component,
|
|
225
|
+
value[i],
|
|
226
|
+
component.name === undefined
|
|
227
|
+
? `${path}[${i}]`
|
|
228
|
+
: `${path}.${component.name}`,
|
|
229
|
+
),
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return normalized;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (isObject(value)) {
|
|
237
|
+
const normalized: NormalizedAbiValue[] = [];
|
|
238
|
+
for (const component of components) {
|
|
239
|
+
const { name } = component;
|
|
240
|
+
|
|
241
|
+
if (name === undefined || name === "") {
|
|
242
|
+
throw new InvalidAbiValueError(
|
|
243
|
+
path,
|
|
244
|
+
type,
|
|
245
|
+
value,
|
|
246
|
+
"invalid tuple value, it has unnamed components so it must be provided as an array",
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const componentPath = `${path}.${name}`;
|
|
251
|
+
|
|
252
|
+
if (!Object.hasOwn(value, name)) {
|
|
253
|
+
throw new InvalidAbiValueError(
|
|
254
|
+
componentPath,
|
|
255
|
+
component.type,
|
|
256
|
+
undefined,
|
|
257
|
+
`missing value for the tuple component "${name}"`,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
normalized.push(
|
|
262
|
+
await normalizeAbiValue(component, value[name], componentPath),
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return normalized;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
throw new InvalidAbiValueError(
|
|
270
|
+
path,
|
|
271
|
+
type,
|
|
272
|
+
value,
|
|
273
|
+
"invalid tuple value, expected an array or an object",
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function normalizeBool(value: unknown, path: string): boolean {
|
|
278
|
+
if (typeof value === "boolean") {
|
|
279
|
+
return value;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Command line arguments always arrive as strings, so the two Solidity
|
|
283
|
+
// literals are accepted. Any other string is rejected.
|
|
284
|
+
if (value === "true") {
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (value === "false") {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
throw new InvalidAbiValueError(path, "bool", value, "invalid boolean value");
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function normalizeAddress(value: unknown, path: string): Promise<string> {
|
|
296
|
+
if (typeof value !== "string") {
|
|
297
|
+
throw new InvalidAbiValueError(
|
|
298
|
+
path,
|
|
299
|
+
"address",
|
|
300
|
+
value,
|
|
301
|
+
"invalid address value, expected a string",
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// The prefix is re-added in lowercase, so that a "0X"-prefixed address still
|
|
306
|
+
// matches the checksummed form it is compared against below.
|
|
307
|
+
const address = getPrefixedHexString(getUnprefixedHexString(value));
|
|
308
|
+
if (!isAddress(address)) {
|
|
309
|
+
throw new InvalidAbiValueError(
|
|
310
|
+
path,
|
|
311
|
+
"address",
|
|
312
|
+
value,
|
|
313
|
+
"invalid address value",
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// A mixed-case address carries an EIP-55 checksum, so it is validated to
|
|
318
|
+
// catch mistyped addresses here instead of failing later, somewhere else.
|
|
319
|
+
// An all-lowercase or all-uppercase one carries no checksum to validate.
|
|
320
|
+
const hexAddress = getUnprefixedHexString(address);
|
|
321
|
+
const isCaseless =
|
|
322
|
+
hexAddress === hexAddress.toLowerCase() ||
|
|
323
|
+
hexAddress === hexAddress.toUpperCase();
|
|
324
|
+
|
|
325
|
+
if (!isCaseless && !(await isValidChecksumAddress(address))) {
|
|
326
|
+
throw new InvalidAbiValueError(
|
|
327
|
+
path,
|
|
328
|
+
"address",
|
|
329
|
+
value,
|
|
330
|
+
"invalid address checksum",
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return address.toLowerCase();
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function normalizeBytes(
|
|
338
|
+
value: unknown,
|
|
339
|
+
path: string,
|
|
340
|
+
type: string,
|
|
341
|
+
length: number | undefined,
|
|
342
|
+
): Uint8Array {
|
|
343
|
+
let bytes: Uint8Array;
|
|
344
|
+
|
|
345
|
+
if (value instanceof Uint8Array) {
|
|
346
|
+
bytes = value;
|
|
347
|
+
// The "0x" prefix is required, as an unprefixed string is more likely to
|
|
348
|
+
// be a value that was meant to be something other than bytes.
|
|
349
|
+
} else if (
|
|
350
|
+
typeof value === "string" &&
|
|
351
|
+
isPrefixedHexString(value) &&
|
|
352
|
+
isHexString(value)
|
|
353
|
+
) {
|
|
354
|
+
const unprefixed = getUnprefixedHexString(value);
|
|
355
|
+
if (unprefixed.length % 2 !== 0) {
|
|
356
|
+
throw new InvalidAbiValueError(
|
|
357
|
+
path,
|
|
358
|
+
type,
|
|
359
|
+
value,
|
|
360
|
+
"invalid bytes value, the hex string has an odd length",
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
bytes =
|
|
364
|
+
unprefixed.length === 0 ? new Uint8Array() : hexStringToBytes(unprefixed);
|
|
365
|
+
} else {
|
|
366
|
+
throw new InvalidAbiValueError(
|
|
367
|
+
path,
|
|
368
|
+
type,
|
|
369
|
+
value,
|
|
370
|
+
'invalid bytes value, expected a "0x"-prefixed hex string or a Uint8Array',
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
if (length !== undefined && bytes.length !== length) {
|
|
375
|
+
throw new InvalidAbiValueError(
|
|
376
|
+
path,
|
|
377
|
+
type,
|
|
378
|
+
value,
|
|
379
|
+
`invalid bytes length, expected ${length} bytes but got ${bytes.length}`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
return bytes;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function normalizeInt(
|
|
387
|
+
value: unknown,
|
|
388
|
+
path: string,
|
|
389
|
+
type: string,
|
|
390
|
+
intType: { signed: boolean; bits: number },
|
|
391
|
+
): bigint {
|
|
392
|
+
let normalized: bigint;
|
|
393
|
+
|
|
394
|
+
if (typeof value === "bigint") {
|
|
395
|
+
normalized = value;
|
|
396
|
+
} else if (typeof value === "number") {
|
|
397
|
+
if (!Number.isSafeInteger(value)) {
|
|
398
|
+
throw new InvalidAbiValueError(
|
|
399
|
+
path,
|
|
400
|
+
type,
|
|
401
|
+
value,
|
|
402
|
+
"invalid numeric value, it is not a safe integer; use a bigint or a string instead",
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
normalized = BigInt(value);
|
|
406
|
+
} else if (typeof value === "string") {
|
|
407
|
+
normalized = parseIntValue(value, path, type);
|
|
408
|
+
} else {
|
|
409
|
+
throw new InvalidAbiValueError(path, type, value, "invalid numeric value");
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const { min, max } = getIntTypeRange(intType);
|
|
413
|
+
if (normalized < min || normalized > max) {
|
|
414
|
+
throw new AbiValueOutOfBoundsError(path, type, value, min, max);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
return normalized;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function parseIntValue(value: string, path: string, type: string): bigint {
|
|
421
|
+
// BigInt() throws on a signed hex string, so the sign is handled here.
|
|
422
|
+
const negative = value.startsWith("-");
|
|
423
|
+
const magnitude = negative ? value.slice(1) : value;
|
|
424
|
+
|
|
425
|
+
if (!DECIMAL_REGEX.test(magnitude) && !HEX_REGEX.test(magnitude)) {
|
|
426
|
+
throw new InvalidAbiValueError(path, type, value, "invalid numeric value");
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const parsed = BigInt(magnitude);
|
|
430
|
+
return negative ? -parsed : parsed;
|
|
431
|
+
}
|
package/src/internal/bytes.ts
CHANGED
|
@@ -20,17 +20,17 @@ export async function parseJsonStream<T>(stream: Readable): Promise<T> {
|
|
|
20
20
|
streamParserJson = await import("@streamparser/json-node");
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
//
|
|
24
|
-
//
|
|
23
|
+
// We only emit the root value, as it's the only one we use, and emitting
|
|
24
|
+
// every nested value is much slower.
|
|
25
25
|
const jsonParser = new streamParserJson.JSONParser({
|
|
26
|
-
|
|
26
|
+
paths: ["$"],
|
|
27
27
|
});
|
|
28
28
|
|
|
29
29
|
const result: T | undefined = await pipeline(
|
|
30
30
|
stream,
|
|
31
31
|
jsonParser,
|
|
32
32
|
async (
|
|
33
|
-
elements: AsyncIterable<StreamParserJson.ParsedElementInfo
|
|
33
|
+
elements: AsyncIterable<StreamParserJson.ParsedElementInfo>,
|
|
34
34
|
): Promise<any | undefined> => {
|
|
35
35
|
let value:
|
|
36
36
|
| StreamParserJson.JsonTypes.JsonPrimitive
|
package/src/internal/fs.ts
CHANGED
|
@@ -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 {
|
|
8
|
-
|
|
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
|
+
}
|
package/src/internal/request.ts
CHANGED
|
@@ -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
|
-
|
|
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}` : ""
|