runtime-reporter 0.4.2 → 0.4.4
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/README.md +47 -44
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -3
- package/dist/index.d.ts +8 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ Getting started is easy. Create a reporter instance with your messages and start
|
|
|
36
36
|
import { createReporter } from "runtime-reporter";
|
|
37
37
|
|
|
38
38
|
const reporter = createReporter({
|
|
39
|
-
ERR01: "MyComponent failed
|
|
39
|
+
ERR01: "MyComponent failed to mount",
|
|
40
40
|
});
|
|
41
41
|
|
|
42
42
|
reporter.error("ERR01");
|
|
@@ -47,10 +47,10 @@ reporter.error("ERR01");
|
|
|
47
47
|
Replace inline strings with centralized, code-based identifiers.
|
|
48
48
|
|
|
49
49
|
```ts
|
|
50
|
-
// Without runtime-reporter (logs "MyComponent failed
|
|
51
|
-
console.error("MyComponent failed
|
|
50
|
+
// Without runtime-reporter (logs "MyComponent failed to mount")
|
|
51
|
+
console.error("MyComponent failed to mount");
|
|
52
52
|
|
|
53
|
-
// With runtime-reporter (logs "MyComponent failed
|
|
53
|
+
// With runtime-reporter (logs "MyComponent failed to mount (ERR01)")
|
|
54
54
|
reporter.error("ERR01");
|
|
55
55
|
```
|
|
56
56
|
|
|
@@ -60,10 +60,10 @@ Inject runtime data into your messages via message templates and tokenized varia
|
|
|
60
60
|
|
|
61
61
|
```ts
|
|
62
62
|
const reporter = createReporter({
|
|
63
|
-
ERR01: "{{ componentName }} failed
|
|
63
|
+
ERR01: "{{ componentName }} failed to mount",
|
|
64
64
|
});
|
|
65
65
|
|
|
66
|
-
reporter.error("ERR01", { componentName: "MyComponent"
|
|
66
|
+
reporter.error("ERR01", { componentName: "MyComponent" });
|
|
67
67
|
```
|
|
68
68
|
|
|
69
69
|
### Type safety
|
|
@@ -73,22 +73,27 @@ Annotate your messages to get autocomplete and compile-time validation for messa
|
|
|
73
73
|
```ts
|
|
74
74
|
const messages: RuntimeReporterMessages<{
|
|
75
75
|
code: "ERR01";
|
|
76
|
-
template: "{{ componentName }} failed
|
|
77
|
-
tokens: "componentName"
|
|
76
|
+
template: "{{ componentName }} failed to mount";
|
|
77
|
+
tokens: "componentName";
|
|
78
78
|
}> = {
|
|
79
|
-
ERR01: "{{ componentName }} failed
|
|
79
|
+
ERR01: "{{ componentName }} failed to mount",
|
|
80
80
|
};
|
|
81
81
|
|
|
82
82
|
const reporter = createReporter(messages);
|
|
83
83
|
|
|
84
|
-
|
|
85
|
-
reporter.error("ERR01", { componentName: "MyComponent" });
|
|
86
|
-
|
|
84
|
+
// ✅ Autocomplete
|
|
85
|
+
reporter.error("ERR01", { componentName: "MyComponent" });
|
|
86
|
+
|
|
87
|
+
// ❌ TypeScript Error: "ERR02" is not a valid message code
|
|
88
|
+
reporter.error("ERR02", { componentName: "MyComponent" });
|
|
89
|
+
|
|
90
|
+
// ❌ TypeScript Error: "componentName" token is required
|
|
91
|
+
reporter.error("ERR01");
|
|
87
92
|
```
|
|
88
93
|
|
|
89
|
-
### Production
|
|
94
|
+
### Production environments
|
|
90
95
|
|
|
91
|
-
Pass an empty object to the `createReporter` function in production for better security and a smaller bundle size.
|
|
96
|
+
Pass an empty object to the `createReporter` function in production environments for better security and a smaller bundle size.
|
|
92
97
|
|
|
93
98
|
```ts
|
|
94
99
|
const reporter = createReporter(
|
|
@@ -107,7 +112,7 @@ it("should log error if component fails to mount", () => {
|
|
|
107
112
|
render(<MyComponent />);
|
|
108
113
|
|
|
109
114
|
expect(console.error).toHaveBeenCalledWith(
|
|
110
|
-
reporter.message("ERR01", { componentName: "MyComponent"
|
|
115
|
+
reporter.message("ERR01", { componentName: "MyComponent" })
|
|
111
116
|
);
|
|
112
117
|
});
|
|
113
118
|
```
|
|
@@ -130,16 +135,22 @@ import { createReporter, type RuntimeReporterMessages } from "runtime-reporter";
|
|
|
130
135
|
const messages: RuntimeReporterMessages<
|
|
131
136
|
| {
|
|
132
137
|
code: "ERR01";
|
|
133
|
-
template: "{{ componentName }} failed
|
|
134
|
-
tokens: "componentName"
|
|
138
|
+
template: "{{ componentName }} failed to mount";
|
|
139
|
+
tokens: "componentName";
|
|
135
140
|
}
|
|
136
141
|
| {
|
|
137
142
|
code: "ERR02";
|
|
138
143
|
template: "Failed to load configuration";
|
|
139
144
|
}
|
|
145
|
+
| {
|
|
146
|
+
code: "ERR03";
|
|
147
|
+
template: "Failed to fetch {{ resource }} from {{ url }}";
|
|
148
|
+
tokens: "resource" | "url";
|
|
149
|
+
}
|
|
140
150
|
> = {
|
|
141
|
-
ERR01: "{{ componentName }} failed
|
|
151
|
+
ERR01: "{{ componentName }} failed to mount",
|
|
142
152
|
ERR02: "Failed to load configuration",
|
|
153
|
+
ERR03: "Failed to fetch {{ resource }} from {{ url }}",
|
|
143
154
|
};
|
|
144
155
|
|
|
145
156
|
/** The runtime reporter for <project-name> */
|
|
@@ -148,7 +159,7 @@ const reporter = createReporter(messages);
|
|
|
148
159
|
export default reporter;
|
|
149
160
|
```
|
|
150
161
|
|
|
151
|
-
Once your project's reporter is created, you can import and use it wherever you need it
|
|
162
|
+
Once your project's reporter is created, you can import and use it wherever you need it like this:
|
|
152
163
|
|
|
153
164
|
```ts
|
|
154
165
|
// src/my-component.ts
|
|
@@ -157,7 +168,7 @@ import { reporter } from "./runtime-reporter";
|
|
|
157
168
|
|
|
158
169
|
export function MyComponent() {
|
|
159
170
|
useEffect(() => {
|
|
160
|
-
reporter.error("ERR01", { componentName: "MyComponent"
|
|
171
|
+
reporter.error("ERR01", { componentName: "MyComponent" });
|
|
161
172
|
}, []);
|
|
162
173
|
|
|
163
174
|
return <div>My Component</div>;
|
|
@@ -204,36 +215,23 @@ const reporter = createReporter(messages, {
|
|
|
204
215
|
formatMessage: (msg, code) => `[${code}] ${msg}`,
|
|
205
216
|
});
|
|
206
217
|
|
|
207
|
-
reporter.message("
|
|
208
|
-
// "[
|
|
218
|
+
reporter.message("ERR01", { componentName: "MyComponent" });
|
|
219
|
+
// "[ERR01] MyComponent failed to mount"
|
|
209
220
|
```
|
|
210
221
|
|
|
211
|
-
###
|
|
222
|
+
### Calling `fail()` in production
|
|
212
223
|
|
|
213
|
-
When the `createReporter` function
|
|
224
|
+
When the `createReporter` function provided an empty message set in production, the `fail` method will use the customizable `defaultTemplate` option which defaults to "An error occurred". This message is intended to be generic so that it does not reveal sensitive information about the system, while still providing a code for debugging purposes.
|
|
214
225
|
|
|
215
226
|
```ts
|
|
216
227
|
const reporter = createReporter(
|
|
217
|
-
// Pass an empty object in production for better security and a smaller bundle size
|
|
218
228
|
process.env.NODE_ENV === "production" ? ({} as typeof messages) : messages
|
|
219
229
|
);
|
|
220
230
|
|
|
221
|
-
reporter.fail("ERR01", { componentName: "Router"
|
|
231
|
+
reporter.fail("ERR01", { componentName: "Router" });
|
|
222
232
|
// throws: "An error occurred (ERR01)"
|
|
223
233
|
```
|
|
224
234
|
|
|
225
|
-
The remaining reporter methods will not log anything in production when the code is missing from the message set.
|
|
226
|
-
|
|
227
|
-
```ts
|
|
228
|
-
const reporter = createReporter(
|
|
229
|
-
// Pass an empty object in production for better security and a smaller bundle size
|
|
230
|
-
process.env.NODE_ENV === "production" ? ({} as typeof messages) : messages
|
|
231
|
-
);
|
|
232
|
-
|
|
233
|
-
reporter.error("ERR01", { componentName: "Router", phase: "mount" });
|
|
234
|
-
// does not log anything
|
|
235
|
-
```
|
|
236
|
-
|
|
237
235
|
### Using `message()` in tests
|
|
238
236
|
|
|
239
237
|
The `message` method returns the resolved string without side effects, allowing you to validate precise messaging without duplicating text.
|
|
@@ -245,7 +243,7 @@ it("should log error if component fails to mount", () => {
|
|
|
245
243
|
render(<MyComponent />);
|
|
246
244
|
|
|
247
245
|
expect(console.error).toHaveBeenCalledWith(
|
|
248
|
-
reporter.message("ERR01", { componentName: "MyComponent"
|
|
246
|
+
reporter.message("ERR01", { componentName: "MyComponent" })
|
|
249
247
|
);
|
|
250
248
|
});
|
|
251
249
|
```
|
|
@@ -258,16 +256,21 @@ You can still get the same benefits as TypeScript by using JSDoc-style type anno
|
|
|
258
256
|
/**
|
|
259
257
|
* @type {import("runtime-reporter").RuntimeReporterMessages<{
|
|
260
258
|
* code: "ERR01";
|
|
261
|
-
* template: "{{ componentName }} failed
|
|
262
|
-
* tokens: "componentName"
|
|
259
|
+
* template: "{{ componentName }} failed to mount";
|
|
260
|
+
* tokens: "componentName";
|
|
263
261
|
* } | {
|
|
264
|
-
* code: "
|
|
265
|
-
* template: "
|
|
262
|
+
* code: "ERR02";
|
|
263
|
+
* template: "Failed to load configuration";
|
|
264
|
+
* } | {
|
|
265
|
+
* code: "ERR03";
|
|
266
|
+
* template: "Failed to fetch {{ resource }} from {{ url }}";
|
|
267
|
+
* tokens: "resource" | "url";
|
|
266
268
|
* }>}
|
|
267
269
|
*/
|
|
268
270
|
const messages = {
|
|
269
271
|
ERR01: "{{ componentName }} failed at {{ phase }}",
|
|
270
|
-
|
|
272
|
+
ERR02: "Failed to load configuration",
|
|
273
|
+
ERR03: "Failed to fetch {{ resource }} from {{ url }}",
|
|
271
274
|
};
|
|
272
275
|
```
|
|
273
276
|
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * The type information for a single runtime reporter message\n * @since v0.1.0\n */\nexport type RuntimeReporterMessage = {\n code: string;\n template: string;\n tokens?: string;\n};\n\n/**\n * The type for a full list of messages with their associated code and template\n * @since v0.1.0\n */\nexport type RuntimeReporterMessages<T extends RuntimeReporterMessage> = {\n [K in T[\"code\"]]: Extract<T, { code: K }>[\"template\"];\n};\n\n/**\n * The type for the supported values of a placeholder token\n * @since v0.1.0\n */\nexport type RuntimeReporterToken = string | number | boolean | Error | null | undefined;\n\n/**\n * The type for a record of placeholder token names and their values\n * @since v0.2.0\n */\nexport type RuntimeReporterTokens = Record<string, RuntimeReporterToken>;\n\n/**\n * A utility type used to determine the second argument of the runtime reporter methods\n * @private\n */\ntype ReporterTokensArgs<T extends RuntimeReporterMessage, U extends T[\"code\"]> = Extract<\n T,\n { code: U }\n>[\"tokens\"] extends infer Tokens\n ? [Tokens] extends [string]\n ? [tokens: Record<Tokens, RuntimeReporterToken>]\n : []\n : [];\n\n/**\n * Return type for message(); displays the template + code in default format on hover.\n * The runtime value is the resolved string (tokens substituted); the type is for DX only.\n * @private\n */\ntype MessageReturnType<T extends RuntimeReporterMessage, U extends T[\"code\"]> =\n Extract<T, { code: U }> extends { template: infer Template }\n ? Template extends string\n ? `${Template} (${U})`\n : string\n : string;\n\n/**\n * The runtime report object with all of it's associated methods; the result\n * of the primary export: `createReporter`\n * @private\n */\ninterface RuntimeReporter<T extends RuntimeReporterMessage> {\n /**\n * Retrieves the full text of the targeted message\n *\n * _Note: As a convenience, the return type will attempt to show the literal type of the template\n * pattern and code suffix (in the default format) for the message on hover; the actual output may\n * vary based on the tokens provided and the `formatMessage` option._\n *\n * _Tip: This method is particularly useful in the test environment; allowing you\n * to make precise assertions without having to duplicate any of the raw message text._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n message<U extends T[\"code\"]>(\n code: U,\n ...args: ReporterTokensArgs<T, U>\n ): MessageReturnType<T, U>;\n\n /**\n * Logs a warning to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n warn<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Logs an error to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n error<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Logs a message to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n log<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Throws an error with the full text of the targeted message in all environments\n *\n * _Note: When the `createReporter` function is called in production with an empty\n * message set, this method will use the \"defaultTemplate\" option in this format: \"<defaultTemplate> (<code>)\"_\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n fail<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n}\n\nexport interface RuntimeReporterOptions {\n /**\n * A hook to format the message text universally. By default, it\n * outputs the message in the following format: \"<message> (<code>)\"\n * @param message The resolved message text; the placeholders have been replaced by their token values\n * @param code The unique code associated with the message\n * @returns The final, fully formatted message\n */\n formatMessage?: (message: string, code: string) => string;\n\n /**\n * The default template to fallback on when a provided code does not\n * have an associated message. Defaults to \"An error occurred\"\n *\n * _Note: This is only used when the `fail` method is called in production\n * environments when the `createReporter` function is provided an empty message set._\n */\n defaultTemplate?: string;\n}\n\n/**\n * Resolves the message text via the message template and the associated tokens\n * @param template The template string for the reported message\n * @param tokens The token names and values for the instance\n * @returns The resolved message text; returns an empty string if the template is falsy\n */\nconst resolveTemplate = function resolveTemplate(\n template: string,\n tokens?: Record<string, RuntimeReporterToken>\n): string {\n let message = template;\n\n if (message) {\n Object.entries(tokens || {}).forEach((entry) => {\n const [token, value] = entry;\n const replace = value instanceof Error ? value.message : String(value ?? \"\");\n const sanitized = token.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n message = message.replace(new RegExp(`\\\\{\\\\{\\\\s*${sanitized}\\\\s*\\\\}\\\\}`, \"g\"), replace);\n });\n }\n\n return message;\n};\n\n/**\n * Creates a reporter object with various helpful runtime methods\n * @param messages The messages record organized by code and template\n * @param options Optional configuration options\n * @returns A runtime report object\n */\nexport function createReporter<T extends RuntimeReporterMessage>(\n messages: RuntimeReporterMessages<T>,\n options: RuntimeReporterOptions = {}\n): RuntimeReporter<T> {\n const {\n formatMessage = (message, code) => `${message} (${code})`,\n defaultTemplate = \"An error occurred\",\n } = options;\n const messagesByCode = messages as Record<string, string>;\n\n /**\n * Retrieves the final message for a give code and its associated tokens\n * @param code The unique code associated with the message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n * @returns The fully resolve message or an empty string if there was no template\n */\n const getMessage = function getMessage(\n code: string,\n ...args: Array<Record<string, RuntimeReporterToken>>\n ): string {\n const template = messagesByCode[code] || defaultTemplate;\n const tokens = args[0];\n const text = resolveTemplate(template, tokens);\n return formatMessage(text, code);\n };\n\n return {\n message: (code, ...args) =>\n getMessage(code, ...args) as MessageReturnType<T, typeof code & T[\"code\"]>,\n error: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.error(message);\n },\n warn: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.warn(message);\n },\n log: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.log(message);\n },\n fail: (code, ...args) => {\n const message = getMessage(code, ...args);\n throw new Error(message);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoJA,IAAM,kBAAkB,SAASA,iBAC7B,UACA,QACM;AACN,MAAI,UAAU;AAEd,MAAI,SAAS;AACT,WAAO,QAAQ,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC,UAAU;AAC5C,YAAM,CAAC,OAAO,KAAK,IAAI;AACvB,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,EAAE;AAC3E,YAAM,YAAY,MAAM,QAAQ,uBAAuB,MAAM;AAC7D,gBAAU,QAAQ,QAAQ,IAAI,OAAO,aAAa,SAAS,cAAc,GAAG,GAAG,OAAO;AAAA,IAC1F,CAAC;AAAA,EACL;AAEA,SAAO;AACX;AAQO,SAAS,eACZ,UACA,UAAkC,CAAC,GACjB;AAClB,QAAM;AAAA,IACF,gBAAgB,CAAC,SAAS,SAAS,GAAG,OAAO,KAAK,IAAI;AAAA,IACtD,kBAAkB;AAAA,EACtB,IAAI;AACJ,QAAM,iBAAiB;AAQvB,QAAM,aAAa,SAASC,YACxB,SACG,MACG;AACN,UAAM,WAAW,eAAe,IAAI,KAAK;AACzC,UAAM,SAAS,KAAK,CAAC;AACrB,UAAM,OAAO,gBAAgB,UAAU,MAAM;AAC7C,WAAO,cAAc,MAAM,IAAI;AAAA,EACnC;AAEA,SAAO;AAAA,IACH,SAAS,CAAC,SAAS,SACf,WAAW,MAAM,GAAG,IAAI;AAAA,IAC5B,OAAO,CAAC,SAAS,SAAS;AACtB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,MAAM,OAAO;AAAA,IACnD;AAAA,IACA,MAAM,CAAC,SAAS,SAAS;AACrB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,KAAK,OAAO;AAAA,IAClD;AAAA,IACA,KAAK,CAAC,SAAS,SAAS;AACpB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,IAAI,OAAO;AAAA,IACjD;AAAA,IACA,MAAM,CAAC,SAAS,SAAS;AACrB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,YAAM,IAAI,MAAM,OAAO;AAAA,IAC3B;AAAA,EACJ;AACJ;","names":["resolveTemplate","getMessage"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * The type information for a single runtime reporter message\n * @since v0.1.0\n */\nexport type RuntimeReporterMessage = {\n code: string;\n template: string;\n tokens?: string;\n};\n\n/**\n * The type for a full list of messages with their associated code and template\n * @since v0.1.0\n */\nexport type RuntimeReporterMessages<T extends RuntimeReporterMessage> = {\n [K in T[\"code\"]]: Extract<T, { code: K }>[\"template\"];\n};\n\n/**\n * The type for the supported values of a placeholder token\n * @since v0.1.0\n */\nexport type RuntimeReporterToken = string | number | boolean | Error | null | undefined;\n\n/**\n * The type for a record of placeholder token names and their values\n * @since v0.2.0\n */\nexport type RuntimeReporterTokens = Record<string, RuntimeReporterToken>;\n\n/**\n * A utility type used to determine the second argument of the runtime reporter methods\n * @private\n */\ntype ReporterTokensArgs<T extends RuntimeReporterMessage, U extends T[\"code\"]> = Extract<\n T,\n { code: U }\n>[\"tokens\"] extends infer Tokens\n ? [Tokens] extends [string]\n ? [tokens: Record<Tokens, RuntimeReporterToken>]\n : []\n : [];\n\n/**\n * Return type for message(); displays the template + code in default format on hover.\n * The runtime value is the resolved string (tokens substituted); the type is for DX only.\n * @private\n */\ntype MessageReturnType<T extends RuntimeReporterMessage, U extends T[\"code\"]> =\n Extract<T, { code: U }> extends { template: infer Template }\n ? Template extends string\n ? `${Template} (${U})`\n : string\n : string;\n\n/**\n * The runtime report object with all of it's associated methods;\n * the result of the primary export: `createReporter`\n * @private\n */\ninterface RuntimeReporter<T extends RuntimeReporterMessage> {\n /**\n * Retrieves the full text of the targeted message\n *\n * _Note: As a convenience, the return type will attempt to show the literal type of the template\n * pattern and code suffix (in the default format) for the message on hover; the actual output may\n * vary based on the tokens provided and the `formatMessage` option._\n *\n * _Tip: This method is particularly useful in the test environment; allowing you\n * to make precise assertions without having to duplicate any of the raw message text._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n message<U extends T[\"code\"]>(\n code: U,\n ...args: ReporterTokensArgs<T, U>\n ): MessageReturnType<T, U>;\n\n /**\n * Logs a warning to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n warn<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Logs an error to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n error<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Logs a message to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n log<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Throws an error with the full text of the targeted message in all environments\n *\n * _Note: When the `createReporter` function is called in production with an empty\n * message set, this method will use the \"defaultTemplate\" option in this format: \"<defaultTemplate> (<code>)\"_\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n fail<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n}\n\n/**\n * The configuration options for createReporter()\n * @since v0.1.0\n */\nexport interface RuntimeReporterOptions {\n /**\n * A hook to format the message text universally. By default, it\n * outputs the message in the following format: \"<message> (<code>)\"\n * @param message The resolved message text; the placeholders have been replaced by their token values\n * @param code The unique code associated with the message\n * @returns The final, fully formatted message\n */\n formatMessage?: (message: string, code: string) => string;\n\n /**\n * The default template to fallback on when a provided code does not\n * have an associated message. Defaults to \"An error occurred\"\n *\n * _Note: This is only used when the `fail` method is called in production\n * environments when the `createReporter` function is provided an empty message set._\n */\n defaultTemplate?: string;\n}\n\n/**\n * Resolves the message text via the message template and the associated tokens\n * @param template The template string for the reported message\n * @param tokens The token names and values for the instance\n * @returns The resolved message text; returns an empty string if the template is falsy\n * @private\n */\nconst resolveTemplate = function resolveTemplate(\n template: string,\n tokens?: Record<string, RuntimeReporterToken>\n): string {\n let message = template;\n\n if (message) {\n Object.entries(tokens || {}).forEach((entry) => {\n const [token, value] = entry;\n const replace = value instanceof Error ? value.message : String(value ?? \"\");\n const sanitized = token.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n message = message.replace(new RegExp(`\\\\{\\\\{\\\\s*${sanitized}\\\\s*\\\\}\\\\}`, \"g\"), replace);\n });\n }\n\n return message;\n};\n\n/**\n * Creates a new runtime reporter object with all of it's associated methods\n * @param messages The messages record organized by code and template\n * @param options Optional configuration options\n * @returns A runtime report object\n * @since v0.1.0\n */\nexport function createReporter<T extends RuntimeReporterMessage>(\n messages: RuntimeReporterMessages<T>,\n options: RuntimeReporterOptions = {}\n): RuntimeReporter<T> {\n const {\n formatMessage = (message, code) => `${message} (${code})`,\n defaultTemplate = \"An error occurred\",\n } = options;\n const messagesByCode = messages as Record<string, string>;\n\n /**\n * Retrieves the final message for a give code and its associated tokens\n * @param code The unique code associated with the message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n * @returns The fully resolve message or an empty string if there was no template\n */\n const getMessage = function getMessage(\n code: string,\n ...args: Array<Record<string, RuntimeReporterToken>>\n ): string {\n const template = messagesByCode[code] || defaultTemplate;\n const tokens = args[0];\n const text = resolveTemplate(template, tokens);\n return formatMessage(text, code);\n };\n\n return {\n message: (code, ...args) =>\n getMessage(code, ...args) as MessageReturnType<T, typeof code & T[\"code\"]>,\n error: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.error(message);\n },\n warn: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.warn(message);\n },\n log: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.log(message);\n },\n fail: (code, ...args) => {\n const message = getMessage(code, ...args);\n throw new Error(message);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAyJA,IAAM,kBAAkB,SAASA,iBAC7B,UACA,QACM;AACN,MAAI,UAAU;AAEd,MAAI,SAAS;AACT,WAAO,QAAQ,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC,UAAU;AAC5C,YAAM,CAAC,OAAO,KAAK,IAAI;AACvB,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,EAAE;AAC3E,YAAM,YAAY,MAAM,QAAQ,uBAAuB,MAAM;AAC7D,gBAAU,QAAQ,QAAQ,IAAI,OAAO,aAAa,SAAS,cAAc,GAAG,GAAG,OAAO;AAAA,IAC1F,CAAC;AAAA,EACL;AAEA,SAAO;AACX;AASO,SAAS,eACZ,UACA,UAAkC,CAAC,GACjB;AAClB,QAAM;AAAA,IACF,gBAAgB,CAAC,SAAS,SAAS,GAAG,OAAO,KAAK,IAAI;AAAA,IACtD,kBAAkB;AAAA,EACtB,IAAI;AACJ,QAAM,iBAAiB;AAQvB,QAAM,aAAa,SAASC,YACxB,SACG,MACG;AACN,UAAM,WAAW,eAAe,IAAI,KAAK;AACzC,UAAM,SAAS,KAAK,CAAC;AACrB,UAAM,OAAO,gBAAgB,UAAU,MAAM;AAC7C,WAAO,cAAc,MAAM,IAAI;AAAA,EACnC;AAEA,SAAO;AAAA,IACH,SAAS,CAAC,SAAS,SACf,WAAW,MAAM,GAAG,IAAI;AAAA,IAC5B,OAAO,CAAC,SAAS,SAAS;AACtB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,MAAM,OAAO;AAAA,IACnD;AAAA,IACA,MAAM,CAAC,SAAS,SAAS;AACrB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,KAAK,OAAO;AAAA,IAClD;AAAA,IACA,KAAK,CAAC,SAAS,SAAS;AACpB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,IAAI,OAAO;AAAA,IACjD;AAAA,IACA,MAAM,CAAC,SAAS,SAAS;AACrB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,YAAM,IAAI,MAAM,OAAO;AAAA,IAC3B;AAAA,EACJ;AACJ;","names":["resolveTemplate","getMessage"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -44,8 +44,8 @@ type MessageReturnType<T extends RuntimeReporterMessage, U extends T["code"]> =
|
|
|
44
44
|
template: infer Template;
|
|
45
45
|
} ? Template extends string ? `${Template} (${U})` : string : string;
|
|
46
46
|
/**
|
|
47
|
-
* The runtime report object with all of it's associated methods;
|
|
48
|
-
* of the primary export: `createReporter`
|
|
47
|
+
* The runtime report object with all of it's associated methods;
|
|
48
|
+
* the result of the primary export: `createReporter`
|
|
49
49
|
* @private
|
|
50
50
|
*/
|
|
51
51
|
interface RuntimeReporter<T extends RuntimeReporterMessage> {
|
|
@@ -102,6 +102,10 @@ interface RuntimeReporter<T extends RuntimeReporterMessage> {
|
|
|
102
102
|
*/
|
|
103
103
|
fail<U extends T["code"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;
|
|
104
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* The configuration options for createReporter()
|
|
107
|
+
* @since v0.1.0
|
|
108
|
+
*/
|
|
105
109
|
interface RuntimeReporterOptions {
|
|
106
110
|
/**
|
|
107
111
|
* A hook to format the message text universally. By default, it
|
|
@@ -121,10 +125,11 @@ interface RuntimeReporterOptions {
|
|
|
121
125
|
defaultTemplate?: string;
|
|
122
126
|
}
|
|
123
127
|
/**
|
|
124
|
-
* Creates a reporter object with
|
|
128
|
+
* Creates a new runtime reporter object with all of it's associated methods
|
|
125
129
|
* @param messages The messages record organized by code and template
|
|
126
130
|
* @param options Optional configuration options
|
|
127
131
|
* @returns A runtime report object
|
|
132
|
+
* @since v0.1.0
|
|
128
133
|
*/
|
|
129
134
|
declare function createReporter<T extends RuntimeReporterMessage>(messages: RuntimeReporterMessages<T>, options?: RuntimeReporterOptions): RuntimeReporter<T>;
|
|
130
135
|
|
package/dist/index.d.ts
CHANGED
|
@@ -44,8 +44,8 @@ type MessageReturnType<T extends RuntimeReporterMessage, U extends T["code"]> =
|
|
|
44
44
|
template: infer Template;
|
|
45
45
|
} ? Template extends string ? `${Template} (${U})` : string : string;
|
|
46
46
|
/**
|
|
47
|
-
* The runtime report object with all of it's associated methods;
|
|
48
|
-
* of the primary export: `createReporter`
|
|
47
|
+
* The runtime report object with all of it's associated methods;
|
|
48
|
+
* the result of the primary export: `createReporter`
|
|
49
49
|
* @private
|
|
50
50
|
*/
|
|
51
51
|
interface RuntimeReporter<T extends RuntimeReporterMessage> {
|
|
@@ -102,6 +102,10 @@ interface RuntimeReporter<T extends RuntimeReporterMessage> {
|
|
|
102
102
|
*/
|
|
103
103
|
fail<U extends T["code"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;
|
|
104
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* The configuration options for createReporter()
|
|
107
|
+
* @since v0.1.0
|
|
108
|
+
*/
|
|
105
109
|
interface RuntimeReporterOptions {
|
|
106
110
|
/**
|
|
107
111
|
* A hook to format the message text universally. By default, it
|
|
@@ -121,10 +125,11 @@ interface RuntimeReporterOptions {
|
|
|
121
125
|
defaultTemplate?: string;
|
|
122
126
|
}
|
|
123
127
|
/**
|
|
124
|
-
* Creates a reporter object with
|
|
128
|
+
* Creates a new runtime reporter object with all of it's associated methods
|
|
125
129
|
* @param messages The messages record organized by code and template
|
|
126
130
|
* @param options Optional configuration options
|
|
127
131
|
* @returns A runtime report object
|
|
132
|
+
* @since v0.1.0
|
|
128
133
|
*/
|
|
129
134
|
declare function createReporter<T extends RuntimeReporterMessage>(messages: RuntimeReporterMessages<T>, options?: RuntimeReporterOptions): RuntimeReporter<T>;
|
|
130
135
|
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * The type information for a single runtime reporter message\n * @since v0.1.0\n */\nexport type RuntimeReporterMessage = {\n code: string;\n template: string;\n tokens?: string;\n};\n\n/**\n * The type for a full list of messages with their associated code and template\n * @since v0.1.0\n */\nexport type RuntimeReporterMessages<T extends RuntimeReporterMessage> = {\n [K in T[\"code\"]]: Extract<T, { code: K }>[\"template\"];\n};\n\n/**\n * The type for the supported values of a placeholder token\n * @since v0.1.0\n */\nexport type RuntimeReporterToken = string | number | boolean | Error | null | undefined;\n\n/**\n * The type for a record of placeholder token names and their values\n * @since v0.2.0\n */\nexport type RuntimeReporterTokens = Record<string, RuntimeReporterToken>;\n\n/**\n * A utility type used to determine the second argument of the runtime reporter methods\n * @private\n */\ntype ReporterTokensArgs<T extends RuntimeReporterMessage, U extends T[\"code\"]> = Extract<\n T,\n { code: U }\n>[\"tokens\"] extends infer Tokens\n ? [Tokens] extends [string]\n ? [tokens: Record<Tokens, RuntimeReporterToken>]\n : []\n : [];\n\n/**\n * Return type for message(); displays the template + code in default format on hover.\n * The runtime value is the resolved string (tokens substituted); the type is for DX only.\n * @private\n */\ntype MessageReturnType<T extends RuntimeReporterMessage, U extends T[\"code\"]> =\n Extract<T, { code: U }> extends { template: infer Template }\n ? Template extends string\n ? `${Template} (${U})`\n : string\n : string;\n\n/**\n * The runtime report object with all of it's associated methods; the result\n * of the primary export: `createReporter`\n * @private\n */\ninterface RuntimeReporter<T extends RuntimeReporterMessage> {\n /**\n * Retrieves the full text of the targeted message\n *\n * _Note: As a convenience, the return type will attempt to show the literal type of the template\n * pattern and code suffix (in the default format) for the message on hover; the actual output may\n * vary based on the tokens provided and the `formatMessage` option._\n *\n * _Tip: This method is particularly useful in the test environment; allowing you\n * to make precise assertions without having to duplicate any of the raw message text._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n message<U extends T[\"code\"]>(\n code: U,\n ...args: ReporterTokensArgs<T, U>\n ): MessageReturnType<T, U>;\n\n /**\n * Logs a warning to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n warn<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Logs an error to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n error<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Logs a message to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n log<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Throws an error with the full text of the targeted message in all environments\n *\n * _Note: When the `createReporter` function is called in production with an empty\n * message set, this method will use the \"defaultTemplate\" option in this format: \"<defaultTemplate> (<code>)\"_\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n fail<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n}\n\nexport interface RuntimeReporterOptions {\n /**\n * A hook to format the message text universally. By default, it\n * outputs the message in the following format: \"<message> (<code>)\"\n * @param message The resolved message text; the placeholders have been replaced by their token values\n * @param code The unique code associated with the message\n * @returns The final, fully formatted message\n */\n formatMessage?: (message: string, code: string) => string;\n\n /**\n * The default template to fallback on when a provided code does not\n * have an associated message. Defaults to \"An error occurred\"\n *\n * _Note: This is only used when the `fail` method is called in production\n * environments when the `createReporter` function is provided an empty message set._\n */\n defaultTemplate?: string;\n}\n\n/**\n * Resolves the message text via the message template and the associated tokens\n * @param template The template string for the reported message\n * @param tokens The token names and values for the instance\n * @returns The resolved message text; returns an empty string if the template is falsy\n */\nconst resolveTemplate = function resolveTemplate(\n template: string,\n tokens?: Record<string, RuntimeReporterToken>\n): string {\n let message = template;\n\n if (message) {\n Object.entries(tokens || {}).forEach((entry) => {\n const [token, value] = entry;\n const replace = value instanceof Error ? value.message : String(value ?? \"\");\n const sanitized = token.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n message = message.replace(new RegExp(`\\\\{\\\\{\\\\s*${sanitized}\\\\s*\\\\}\\\\}`, \"g\"), replace);\n });\n }\n\n return message;\n};\n\n/**\n * Creates a reporter object with various helpful runtime methods\n * @param messages The messages record organized by code and template\n * @param options Optional configuration options\n * @returns A runtime report object\n */\nexport function createReporter<T extends RuntimeReporterMessage>(\n messages: RuntimeReporterMessages<T>,\n options: RuntimeReporterOptions = {}\n): RuntimeReporter<T> {\n const {\n formatMessage = (message, code) => `${message} (${code})`,\n defaultTemplate = \"An error occurred\",\n } = options;\n const messagesByCode = messages as Record<string, string>;\n\n /**\n * Retrieves the final message for a give code and its associated tokens\n * @param code The unique code associated with the message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n * @returns The fully resolve message or an empty string if there was no template\n */\n const getMessage = function getMessage(\n code: string,\n ...args: Array<Record<string, RuntimeReporterToken>>\n ): string {\n const template = messagesByCode[code] || defaultTemplate;\n const tokens = args[0];\n const text = resolveTemplate(template, tokens);\n return formatMessage(text, code);\n };\n\n return {\n message: (code, ...args) =>\n getMessage(code, ...args) as MessageReturnType<T, typeof code & T[\"code\"]>,\n error: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.error(message);\n },\n warn: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.warn(message);\n },\n log: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.log(message);\n },\n fail: (code, ...args) => {\n const message = getMessage(code, ...args);\n throw new Error(message);\n },\n };\n}\n"],"mappings":";AAoJA,IAAM,kBAAkB,SAASA,iBAC7B,UACA,QACM;AACN,MAAI,UAAU;AAEd,MAAI,SAAS;AACT,WAAO,QAAQ,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC,UAAU;AAC5C,YAAM,CAAC,OAAO,KAAK,IAAI;AACvB,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,EAAE;AAC3E,YAAM,YAAY,MAAM,QAAQ,uBAAuB,MAAM;AAC7D,gBAAU,QAAQ,QAAQ,IAAI,OAAO,aAAa,SAAS,cAAc,GAAG,GAAG,OAAO;AAAA,IAC1F,CAAC;AAAA,EACL;AAEA,SAAO;AACX;AAQO,SAAS,eACZ,UACA,UAAkC,CAAC,GACjB;AAClB,QAAM;AAAA,IACF,gBAAgB,CAAC,SAAS,SAAS,GAAG,OAAO,KAAK,IAAI;AAAA,IACtD,kBAAkB;AAAA,EACtB,IAAI;AACJ,QAAM,iBAAiB;AAQvB,QAAM,aAAa,SAASC,YACxB,SACG,MACG;AACN,UAAM,WAAW,eAAe,IAAI,KAAK;AACzC,UAAM,SAAS,KAAK,CAAC;AACrB,UAAM,OAAO,gBAAgB,UAAU,MAAM;AAC7C,WAAO,cAAc,MAAM,IAAI;AAAA,EACnC;AAEA,SAAO;AAAA,IACH,SAAS,CAAC,SAAS,SACf,WAAW,MAAM,GAAG,IAAI;AAAA,IAC5B,OAAO,CAAC,SAAS,SAAS;AACtB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,MAAM,OAAO;AAAA,IACnD;AAAA,IACA,MAAM,CAAC,SAAS,SAAS;AACrB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,KAAK,OAAO;AAAA,IAClD;AAAA,IACA,KAAK,CAAC,SAAS,SAAS;AACpB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,IAAI,OAAO;AAAA,IACjD;AAAA,IACA,MAAM,CAAC,SAAS,SAAS;AACrB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,YAAM,IAAI,MAAM,OAAO;AAAA,IAC3B;AAAA,EACJ;AACJ;","names":["resolveTemplate","getMessage"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * The type information for a single runtime reporter message\n * @since v0.1.0\n */\nexport type RuntimeReporterMessage = {\n code: string;\n template: string;\n tokens?: string;\n};\n\n/**\n * The type for a full list of messages with their associated code and template\n * @since v0.1.0\n */\nexport type RuntimeReporterMessages<T extends RuntimeReporterMessage> = {\n [K in T[\"code\"]]: Extract<T, { code: K }>[\"template\"];\n};\n\n/**\n * The type for the supported values of a placeholder token\n * @since v0.1.0\n */\nexport type RuntimeReporterToken = string | number | boolean | Error | null | undefined;\n\n/**\n * The type for a record of placeholder token names and their values\n * @since v0.2.0\n */\nexport type RuntimeReporterTokens = Record<string, RuntimeReporterToken>;\n\n/**\n * A utility type used to determine the second argument of the runtime reporter methods\n * @private\n */\ntype ReporterTokensArgs<T extends RuntimeReporterMessage, U extends T[\"code\"]> = Extract<\n T,\n { code: U }\n>[\"tokens\"] extends infer Tokens\n ? [Tokens] extends [string]\n ? [tokens: Record<Tokens, RuntimeReporterToken>]\n : []\n : [];\n\n/**\n * Return type for message(); displays the template + code in default format on hover.\n * The runtime value is the resolved string (tokens substituted); the type is for DX only.\n * @private\n */\ntype MessageReturnType<T extends RuntimeReporterMessage, U extends T[\"code\"]> =\n Extract<T, { code: U }> extends { template: infer Template }\n ? Template extends string\n ? `${Template} (${U})`\n : string\n : string;\n\n/**\n * The runtime report object with all of it's associated methods;\n * the result of the primary export: `createReporter`\n * @private\n */\ninterface RuntimeReporter<T extends RuntimeReporterMessage> {\n /**\n * Retrieves the full text of the targeted message\n *\n * _Note: As a convenience, the return type will attempt to show the literal type of the template\n * pattern and code suffix (in the default format) for the message on hover; the actual output may\n * vary based on the tokens provided and the `formatMessage` option._\n *\n * _Tip: This method is particularly useful in the test environment; allowing you\n * to make precise assertions without having to duplicate any of the raw message text._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n message<U extends T[\"code\"]>(\n code: U,\n ...args: ReporterTokensArgs<T, U>\n ): MessageReturnType<T, U>;\n\n /**\n * Logs a warning to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n warn<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Logs an error to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n error<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Logs a message to the console with the full text of the targeted message in non-production environments\n *\n * _Note: This method will only log when the message associated with the code is found;\n * meaning it will not be called in production if the `createReporter` function\n * is provided an empty message set._\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n log<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n\n /**\n * Throws an error with the full text of the targeted message in all environments\n *\n * _Note: When the `createReporter` function is called in production with an empty\n * message set, this method will use the \"defaultTemplate\" option in this format: \"<defaultTemplate> (<code>)\"_\n * @param code A direct reference to the unique code for the targeted message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n */\n fail<U extends T[\"code\"]>(code: U, ...args: ReporterTokensArgs<T, U>): void;\n}\n\n/**\n * The configuration options for createReporter()\n * @since v0.1.0\n */\nexport interface RuntimeReporterOptions {\n /**\n * A hook to format the message text universally. By default, it\n * outputs the message in the following format: \"<message> (<code>)\"\n * @param message The resolved message text; the placeholders have been replaced by their token values\n * @param code The unique code associated with the message\n * @returns The final, fully formatted message\n */\n formatMessage?: (message: string, code: string) => string;\n\n /**\n * The default template to fallback on when a provided code does not\n * have an associated message. Defaults to \"An error occurred\"\n *\n * _Note: This is only used when the `fail` method is called in production\n * environments when the `createReporter` function is provided an empty message set._\n */\n defaultTemplate?: string;\n}\n\n/**\n * Resolves the message text via the message template and the associated tokens\n * @param template The template string for the reported message\n * @param tokens The token names and values for the instance\n * @returns The resolved message text; returns an empty string if the template is falsy\n * @private\n */\nconst resolveTemplate = function resolveTemplate(\n template: string,\n tokens?: Record<string, RuntimeReporterToken>\n): string {\n let message = template;\n\n if (message) {\n Object.entries(tokens || {}).forEach((entry) => {\n const [token, value] = entry;\n const replace = value instanceof Error ? value.message : String(value ?? \"\");\n const sanitized = token.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n message = message.replace(new RegExp(`\\\\{\\\\{\\\\s*${sanitized}\\\\s*\\\\}\\\\}`, \"g\"), replace);\n });\n }\n\n return message;\n};\n\n/**\n * Creates a new runtime reporter object with all of it's associated methods\n * @param messages The messages record organized by code and template\n * @param options Optional configuration options\n * @returns A runtime report object\n * @since v0.1.0\n */\nexport function createReporter<T extends RuntimeReporterMessage>(\n messages: RuntimeReporterMessages<T>,\n options: RuntimeReporterOptions = {}\n): RuntimeReporter<T> {\n const {\n formatMessage = (message, code) => `${message} (${code})`,\n defaultTemplate = \"An error occurred\",\n } = options;\n const messagesByCode = messages as Record<string, string>;\n\n /**\n * Retrieves the final message for a give code and its associated tokens\n * @param code The unique code associated with the message\n * @param args The remaining optional argument for the function; a record containing the placeholder token values\n * @returns The fully resolve message or an empty string if there was no template\n */\n const getMessage = function getMessage(\n code: string,\n ...args: Array<Record<string, RuntimeReporterToken>>\n ): string {\n const template = messagesByCode[code] || defaultTemplate;\n const tokens = args[0];\n const text = resolveTemplate(template, tokens);\n return formatMessage(text, code);\n };\n\n return {\n message: (code, ...args) =>\n getMessage(code, ...args) as MessageReturnType<T, typeof code & T[\"code\"]>,\n error: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.error(message);\n },\n warn: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.warn(message);\n },\n log: (code, ...args) => {\n const message = getMessage(code, ...args);\n if (messagesByCode[code]) console.log(message);\n },\n fail: (code, ...args) => {\n const message = getMessage(code, ...args);\n throw new Error(message);\n },\n };\n}\n"],"mappings":";AAyJA,IAAM,kBAAkB,SAASA,iBAC7B,UACA,QACM;AACN,MAAI,UAAU;AAEd,MAAI,SAAS;AACT,WAAO,QAAQ,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC,UAAU;AAC5C,YAAM,CAAC,OAAO,KAAK,IAAI;AACvB,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,EAAE;AAC3E,YAAM,YAAY,MAAM,QAAQ,uBAAuB,MAAM;AAC7D,gBAAU,QAAQ,QAAQ,IAAI,OAAO,aAAa,SAAS,cAAc,GAAG,GAAG,OAAO;AAAA,IAC1F,CAAC;AAAA,EACL;AAEA,SAAO;AACX;AASO,SAAS,eACZ,UACA,UAAkC,CAAC,GACjB;AAClB,QAAM;AAAA,IACF,gBAAgB,CAAC,SAAS,SAAS,GAAG,OAAO,KAAK,IAAI;AAAA,IACtD,kBAAkB;AAAA,EACtB,IAAI;AACJ,QAAM,iBAAiB;AAQvB,QAAM,aAAa,SAASC,YACxB,SACG,MACG;AACN,UAAM,WAAW,eAAe,IAAI,KAAK;AACzC,UAAM,SAAS,KAAK,CAAC;AACrB,UAAM,OAAO,gBAAgB,UAAU,MAAM;AAC7C,WAAO,cAAc,MAAM,IAAI;AAAA,EACnC;AAEA,SAAO;AAAA,IACH,SAAS,CAAC,SAAS,SACf,WAAW,MAAM,GAAG,IAAI;AAAA,IAC5B,OAAO,CAAC,SAAS,SAAS;AACtB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,MAAM,OAAO;AAAA,IACnD;AAAA,IACA,MAAM,CAAC,SAAS,SAAS;AACrB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,KAAK,OAAO;AAAA,IAClD;AAAA,IACA,KAAK,CAAC,SAAS,SAAS;AACpB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,UAAI,eAAe,IAAI,EAAG,SAAQ,IAAI,OAAO;AAAA,IACjD;AAAA,IACA,MAAM,CAAC,SAAS,SAAS;AACrB,YAAM,UAAU,WAAW,MAAM,GAAG,IAAI;AACxC,YAAM,IAAI,MAAM,OAAO;AAAA,IAC3B;AAAA,EACJ;AACJ;","names":["resolveTemplate","getMessage"]}
|