@nomicfoundation/hardhat-errors 3.0.0-next.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/src/errors.ts ADDED
@@ -0,0 +1,275 @@
1
+ import type { ErrorDescriptor } from "./descriptors.js";
2
+
3
+ import { CustomError } from "@nomicfoundation/hardhat-utils/error";
4
+ import { isObject } from "@nomicfoundation/hardhat-utils/lang";
5
+
6
+ import { ERRORS } from "./descriptors.js";
7
+
8
+ export type ErrorMessageTemplateValue =
9
+ | string
10
+ | number
11
+ | boolean
12
+ | bigint
13
+ | undefined
14
+ | null
15
+ | ErrorMessageTemplateValue[]
16
+ | { toString(): string };
17
+
18
+ export type MessagetTemplateArguments<MessageTemplateT extends string> =
19
+ MessageTemplateT extends `${string}{${infer Tag}}${infer Rest}`
20
+ ? {
21
+ [K in
22
+ | Tag
23
+ | keyof MessagetTemplateArguments<Rest>]: ErrorMessageTemplateValue;
24
+ }
25
+ : {};
26
+
27
+ export type HardhatErrorConstructorArguments<
28
+ ErrorDescriptorT extends ErrorDescriptor,
29
+ > = keyof MessagetTemplateArguments<
30
+ ErrorDescriptorT["messageTemplate"]
31
+ > extends never
32
+ ? [ErrorDescriptorT, Error?]
33
+ : [
34
+ ErrorDescriptorT,
35
+ MessagetTemplateArguments<ErrorDescriptorT["messageTemplate"]>,
36
+ Error?,
37
+ ];
38
+
39
+ export const ERROR_PREFIX = "HHE";
40
+
41
+ const IS_HARDHAT_ERROR_PROPERTY_NAME = "_isHardhatError";
42
+ const IS_HARDHAT_PLUGIN_ERROR_PROPERTY_NAME = "_isHardhatPluginError";
43
+
44
+ /**
45
+ * An error thrown by Hardhat. This error is meant to be thrown by Hardhat
46
+ * itself, and internal plugins. For errors thrown by community plugins, see
47
+ * `HardhatPluginError`.
48
+ */
49
+ export class HardhatError<
50
+ ErrorDescriptorT extends ErrorDescriptor = ErrorDescriptor,
51
+ > extends CustomError {
52
+ public static readonly ERRORS: typeof ERRORS = ERRORS;
53
+
54
+ readonly #descriptor: ErrorDescriptorT;
55
+
56
+ readonly #arguments: MessagetTemplateArguments<
57
+ ErrorDescriptorT["messageTemplate"]
58
+ >;
59
+
60
+ readonly #errorCode: string;
61
+
62
+ readonly #formattedMessage: string;
63
+
64
+ constructor(
65
+ ...[
66
+ errorDescriptor,
67
+ messageArgumentsOrParentError,
68
+ parentError,
69
+ ]: HardhatErrorConstructorArguments<ErrorDescriptorT>
70
+ ) {
71
+ const errorCode = getErrorCode(errorDescriptor);
72
+
73
+ const formattedMessage =
74
+ messageArgumentsOrParentError === undefined ||
75
+ messageArgumentsOrParentError instanceof Error
76
+ ? errorDescriptor.messageTemplate
77
+ : applyErrorMessageTemplate(
78
+ errorDescriptor.messageTemplate,
79
+ messageArgumentsOrParentError,
80
+ );
81
+
82
+ super(
83
+ `${errorCode}: ${formattedMessage}`,
84
+ parentError instanceof Error
85
+ ? parentError
86
+ : messageArgumentsOrParentError instanceof Error
87
+ ? messageArgumentsOrParentError
88
+ : undefined,
89
+ );
90
+
91
+ this.#descriptor = errorDescriptor;
92
+ this.#errorCode = errorCode;
93
+ this.#formattedMessage = formattedMessage;
94
+
95
+ if (
96
+ messageArgumentsOrParentError === undefined ||
97
+ messageArgumentsOrParentError instanceof Error
98
+ ) {
99
+ /* eslint-disable @typescript-eslint/consistent-type-assertions --
100
+ Typescript inference get's lost here, but we know that if we didn't get
101
+ arguments, it's because the error doesn't have any. */
102
+ this.#arguments = {} as MessagetTemplateArguments<
103
+ ErrorDescriptorT["messageTemplate"]
104
+ >;
105
+ } else {
106
+ this.#arguments = messageArgumentsOrParentError;
107
+ }
108
+
109
+ // As this package is going to be used from most of our packages, there's a
110
+ // change of users having multiple versions of it. If that happens, they may
111
+ // have multiple `HardhatError` classes, so we can't reliably use
112
+ // `instanceof` to check if an error is a `HardhatError`. We define a
113
+ // pseudo-private field to use it for it. While this is not bulletproof, it
114
+ // should be enough for our case, as we won't be changing this class often.
115
+ Object.defineProperty(this, IS_HARDHAT_ERROR_PROPERTY_NAME, {
116
+ configurable: false,
117
+ enumerable: false,
118
+ writable: false,
119
+ value: true,
120
+ });
121
+ }
122
+
123
+ public static isHardhatError(
124
+ other: unknown,
125
+ ): other is HardhatError<ErrorDescriptor>;
126
+ public static isHardhatError<ErrorDescriptorT extends ErrorDescriptor>(
127
+ other: unknown,
128
+ descriptor?: ErrorDescriptorT,
129
+ ): other is HardhatError<ErrorDescriptorT>;
130
+ public static isHardhatError(
131
+ other: unknown,
132
+ descriptor?: ErrorDescriptor,
133
+ ): other is HardhatError<ErrorDescriptor> {
134
+ if (!isObject(other)) {
135
+ return false;
136
+ }
137
+
138
+ const isHardhatErrorProperty = Object.getOwnPropertyDescriptor(
139
+ other,
140
+ IS_HARDHAT_ERROR_PROPERTY_NAME,
141
+ );
142
+
143
+ return (
144
+ isHardhatErrorProperty?.value === true &&
145
+ // If an error descriptor is provided, check if its number matches the Hardhat error number
146
+ (descriptor === undefined
147
+ ? true
148
+ : "number" in other && other.number === descriptor.number)
149
+ );
150
+ }
151
+
152
+ public get number(): number {
153
+ return this.#descriptor.number;
154
+ }
155
+
156
+ public get pluginId(): string | undefined {
157
+ return this.#descriptor.pluginId;
158
+ }
159
+
160
+ public get descriptor(): ErrorDescriptor {
161
+ return this.#descriptor;
162
+ }
163
+
164
+ public get messageArguments(): MessagetTemplateArguments<
165
+ ErrorDescriptorT["messageTemplate"]
166
+ > {
167
+ return this.#arguments;
168
+ }
169
+
170
+ public get errorCode(): string {
171
+ return this.#errorCode;
172
+ }
173
+
174
+ public get formattedMessage(): string {
175
+ return this.#formattedMessage;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * An error thrown by a Hardhat plugin. This error is meant to be thrown by
181
+ * community plugins to signal that something went wrong.
182
+ */
183
+ export class HardhatPluginError extends CustomError {
184
+ constructor(
185
+ public readonly pluginId: string,
186
+ message: string,
187
+ parentError?: Error,
188
+ ) {
189
+ super(message, parentError);
190
+
191
+ // See `HardhatError` constructor for an explanation of this property.
192
+ Object.defineProperty(this, IS_HARDHAT_PLUGIN_ERROR_PROPERTY_NAME, {
193
+ configurable: false,
194
+ enumerable: false,
195
+ writable: false,
196
+ value: true,
197
+ });
198
+ }
199
+
200
+ public static isHardhatPluginError(
201
+ other: unknown,
202
+ ): other is HardhatPluginError {
203
+ if (!isObject(other)) {
204
+ return false;
205
+ }
206
+
207
+ const isHardhatPluginErrorProperty = Object.getOwnPropertyDescriptor(
208
+ other,
209
+ IS_HARDHAT_PLUGIN_ERROR_PROPERTY_NAME,
210
+ );
211
+
212
+ return isHardhatPluginErrorProperty?.value === true;
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Asserts an internal invariant.
218
+ *
219
+ * @param invariant The condition to check.
220
+ * @param message A message to show if the condition is false.
221
+ */
222
+ export function assertHardhatInvariant(
223
+ invariant: boolean,
224
+ message: string,
225
+ ): asserts invariant {
226
+ if (!invariant) {
227
+ throw new HardhatError(ERRORS.INTERNAL.ASSERTION_ERROR, { message });
228
+ }
229
+ }
230
+
231
+ function getErrorCode(errorDescriptor: ErrorDescriptor): string {
232
+ return `${ERROR_PREFIX}${errorDescriptor.number}`;
233
+ }
234
+
235
+ /**
236
+ * This function applies error messages templates like this:
237
+ *
238
+ * - Template is a string which contains a variable tags. A variable tag is a
239
+ * a variable name surrounded by %. Eg: %plugin1%
240
+ * - A variable name is a string of alphanumeric ascii characters.
241
+ * - Every variable tag is replaced by its value.
242
+ * - %% is replaced by %.
243
+ * - Values can't contain variable tags.
244
+ * - If a variable is not present in the template, but present in the values
245
+ * object, an error is thrown.
246
+ *
247
+ * @param template The template string.
248
+ * @param values A map of variable names to their values.
249
+ */
250
+ export function applyErrorMessageTemplate(
251
+ template: string,
252
+ values: Record<string, ErrorMessageTemplateValue>,
253
+ ): string {
254
+ return template.replaceAll(/{(.*?)}/g, (_match, variableName) => {
255
+ const rawValue = values[variableName];
256
+
257
+ if (rawValue === undefined) {
258
+ return "undefined";
259
+ }
260
+
261
+ if (rawValue === null) {
262
+ return "null";
263
+ }
264
+
265
+ if (typeof rawValue === "bigint") {
266
+ return `${rawValue}n`;
267
+ }
268
+
269
+ if (Array.isArray(rawValue)) {
270
+ return JSON.stringify(rawValue);
271
+ }
272
+
273
+ return rawValue.toString();
274
+ });
275
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export type { ErrorDescriptor } from "./descriptors.js";
2
+ export {
3
+ HardhatError,
4
+ HardhatPluginError,
5
+ assertHardhatInvariant,
6
+ } from "./errors.js";