@lokalise/node-core 14.6.1 → 14.7.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/README.md CHANGED
@@ -1,211 +1,252 @@
1
- # node-core 🧬
2
-
3
- Core libraries for Node.js backend services.
4
-
5
- - [Default Logging Configuration](#default-logging-configuration)
6
- - [ConfigScope](#configscope)
7
- - [Error Handling](#error-handling)
8
-
9
- See [docs](/docs) for further instructions on how to use.
10
-
11
- ## Default Logging Configuration
12
-
13
- The library provides methods to resolve the default logging configuration. Public methods available are:
14
-
15
- - `resolveLoggerConfiguration()`, which accepts as parameter an `appConfig`, defined by the `logLevel` and the `nodeEnv`. If the environment is production, the output will be logged in JSON format to be friendly with any data storage. Otherwise, the output will be logged with coloring and formatting to be visible for debugging purposes and help developers.
16
-
17
- The method returns a logger configuration that should be used with `pino` library as in the following example:
18
-
19
- ```ts
20
- const loggerConfig = resolveLoggerConfiguration({
21
- logLevel: 'warn',
22
- nodeEnv: 'production',
23
- redact: {
24
- paths: ['path1', 'path2'],
25
- },
26
- })
27
-
28
- const logger = pino(loggerConfig)
29
- ```
30
-
31
- - `resolveMonorepoLoggerConfiguration()`, which accepts as parameter an `appConfig`, defined by the `logLevel` and the `nodeEnv`. It mostly behaves the same as `resolveLoggerConfiguration`, with the exception of execution in `development environments`. Since monorepo services are usually ran concurrently, logs from `stdout` aren't easily accessible. For this reason this logging configuration writes development logs into files.
32
-
33
- The method returns a logger configuration that should be used with `pino` library as in the following example:
34
-
35
- ```ts
36
- const loggerConfig = resolveMonorepoLoggerConfiguration({
37
- logLevel: 'warn',
38
- nodeEnv: 'production',
39
- append: false,
40
- // targetFile: './logs/service.log' -- optional parameter, you can specify exact path for writing logs
41
- })
42
-
43
- const logger = pino(loggerConfig)
44
- ```
45
-
46
- ## ConfigScope
47
-
48
- `ConfigScope` is a class that provides a way to encapsulate a single config source (e. g. `process.env`) and produce a set of values out of it, defining constraints and transformations for them.
49
-
50
- Once the class is instantiated, you can leverage the following `ConfigScope` methods:
51
-
52
- ### Configuration Parameters by zod schema
53
-
54
- - `getBySchema()`, uses zod schema to validate configuration parameter, the returned type is inferred from the schema
55
- - `param`, the configuration parameter name;
56
- - `schema`, zod schema to use for parsing and validation;
57
-
58
- > **Note:** Starting from version 14, the library requires Zod v4 API usage, to continue using Zod v3 API, please use version 13 of the library.
59
-
60
- ### Mandatory Configuration Parameters
61
-
62
- - `getMandatory()`, returns the value of a mandatory configuration parameter. If the value is missing, an `InternalError` is thrown. Parameters are:
63
- - `param`, the configuration parameter name;
64
- - `getMandatoryInteger()`, returns the value of a mandatory configuration parameter and validates that it is an integer number. If the value is missing or is not an integer, an `InternalError` is thrown. Parameters are:
65
- - `param`, the configuration parameter name;
66
- - `getMandatoryNumber()`, returns the value of a mandatory configuration parameter and validates that it is a number. If the value is missing or is not a number, an `InternalError` is thrown. Parameters are:
67
- - `param`, the configuration parameter name;
68
- - `getMandatoryOneOf()`, returns the value a mandatory configuration parameter and validates that it is one of the supported values. If the value is missing or is not supported, an `InternalError` is thrown. The method also serves as a type guard, narrowing the type of the passed value down to one of the supported options. Parameters are:
69
- - `param`, the configuration parameter name;
70
- - `supportedValues`;
71
- - `getMandatoryValidatedInteger()`, similar to `getMandatoryInteger()`, but also takes a `validator` in input and will throw an `InternalError` if the number is not valid. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
72
- - `param`, the configuration parameter name;
73
- - `validator`;
74
- - `getMandatoryValidatedNumber()`, similar to `getMandatoryNumber()`, but also takes a `validator` in input and will throw an `InternalError` if the number is not valid. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
75
- - `param`, the configuration parameter name;
76
- - `validator`;
77
- - `getMandatoryTransformed()`, calls `getMandatory()` and returns the result of the `transformer` function applied to the configuration parameter value. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
78
- - `param`, the configuration parameter name;
79
- - `transformer`.
80
-
81
- ### Optional Configuration Parameters
82
-
83
- - `getOptionalNullable()`, returns the value of an optional configuration parameter. If the value is missing, it is set to the provided default value.Parameters are:
84
- - `param`, the configuration parameter name;
85
- - `defaultValue`, which can be nullable;
86
- - `getOptional()`, similar to `getOptionalNullable()`, but `defaultValue` cannot be nullable. The return value is always a string;
87
- - `getOptionalNullableInteger()`, returns the value of an optional configuration parameter and validates that it is an integer number. If the value is missing, it is set to the provided default value. If it is not a number, an `InternalError` is thrown. Parameters are:
88
- - `param`, the configuration parameter name;
89
- - `defaultValue`, which can be nullable;
90
- - `getOptionalNullableNumber()`, returns the value of an optional configuration parameter and validates that it is a number. If the value is missing, it is set to the provided default value. If it is not a number, an `InternalError` is thrown. Parameters are:
91
- - `param`, the configuration parameter name;
92
- - `defaultValue`, which can be nullable;
93
- - `getOptionalInteger`, similar to `getOptionalNullableInteger()`, but `defaultValue` cannot be nullable. The return value is always a number;
94
- - `getOptionalNumber`, similar to `getOptionalNullableNumber()`, but `defaultValue` cannot be nullable. The return value is always a number;
95
- - `getOptionalValidated()`, similar to `getOptional()`, but also takes a `validator` in input and will throw an `InternalError` if the value is not valid. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
96
- - `param`, the configuration parameter name;
97
- - `validator`;
98
- - `getOptionalValidatedInteger()`, similar to `getOptionalValidated()`, but expects and returns an integer `number` instead. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
99
- - `param`, the configuration parameter name;
100
- - `validator`;
101
- - `getOptionalValidatedNumber()`, similar to `getOptionalValidated()`, but expects and returns `number` instead. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
102
- - `param`, the configuration parameter name;
103
- - `validator`;
104
- - `getOptionalTransformed()`, similar to `getOptional()`, but also takes a `transformer` in input and the result of the `transformer` function applied to the configuration parameter value. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
105
- - `param`, the configuration parameter name;
106
- - `defaultValue`,
107
- - `transformer`;
108
- - `getOptionalBoolean()`, returns the value of an optional configuration parameter and validates that it is a boolean. It the value is missing, it is assigned the `defaultValue`. If it is not a boolean, an `InternalError` is thrown. Parameters are:
109
- - `param`, the configuration parameter name;
110
- - `defaultValue`.
111
- - `getOptionalOneOf()`, returns the value of an optional configuration parameter, if the value is missing, it falls back to the specified default value, and validates that it is one of the supported values. If the value is not supported, an `InternalError` is thrown. Parameters are:
112
- - `param`, the configuration parameter name;
113
- - `defaultValue`
114
- - `supportedValues`;
115
-
116
- ### Environment Configuration Parameter
117
-
118
- - `isProduction()`, returns true if the environment is production;
119
- - `isDevelopment()`, returns true if the environment is **not** production;
120
- - `isTest()`, returns true if the environment is test.
121
-
122
- ---
123
-
124
- ### Validators and Transformers
125
-
126
- Ad-hoc validators and transformers can be built leveraging the `EnvValueValidator` and the `EnvValueTransformer` types exposed by the library. Alternatively, the following validators and transformers are already provided out of the box:
127
-
128
- #### Validators
129
-
130
- - `createRangeValidator()`, which accepts `greaterOrEqualThan` and `lessOrEqualThan` and validates that a numeric value ranges between those numbers.
131
-
132
- #### Transformers
133
-
134
- - `ensureClosingSlashTransformer()`, which accepts a `value` as parameter, that can be a string or nullable, and adds a closing slash if it is missing and the value is defined.
135
-
136
- ## Error Handling
137
-
138
- The library provides classes and methods for error handling.
139
-
140
- ### Global Error Handler
141
-
142
- Public methods to leverage a global error handler are provided to be used when the process is run outside of the context of the request (e. g. in a queue where no one would catch an error if thrown):
143
-
144
- - `resolveGlobalErrorLogObject()`, which accepts `err` and optionally `correlationID` as parameters and converts the plain error into a serializable object. If the error is not a built-in `Error` type and doesn't have any message, a fixed string is returned instead;
145
- - `executeAndHandleGlobalErrors()`, which accepts the `operation` parameter and will return the result of executing such operation. If an error is thrown during the execution of the operation, `resolveGlobalErrorLogObject()` is called to log the error and the process is terminated;
146
- - `executeAsyncAndHandleGlobalErrors()`, which accepts `operation` and optionally `stopOnError` as parameters and will return the result of executing such operation **asynchronously**. If an error is thrown during the execution of the operation, `resolveGlobalErrorLogObject()` is called to log the error and the process is terminated only if `stopOnError` is `true`. `stopOnError` defaults to `true` if not provided.
147
-
148
- ### Errors
149
-
150
- The library exposes classes for the following errors:
151
-
152
- - `InternalError`, which issues a `500` status code and is not exposed in the global error handler. It expects the following parameters:
153
- - `message`;
154
- - `errorCode`;
155
- - `details` – (optional);
156
- - `cause` – (optional).
157
- - `PublicNonRecoverableError`, which issues the HTTP status code provided and signals that the user did something wrong, hence the error is returned to the consumer of the API. It expects the following parameters:
158
- - `message`;
159
- - `errorCode`;
160
- - `details` – (optional);
161
- - `cause` – (optional);
162
- - `httpStatusCode` – (optional). Defaults to `500`;
163
-
164
- ### Either
165
-
166
- The library provides the type `Either` for error handling in the functional paradigm. The two possible values are:
167
-
168
- - `result` is defined, `error` is undefined;
169
- - `error` is defined, `result` is undefined.
170
-
171
- It's up to the caller of the function to handle the received error or throw an error.
172
-
173
- Read [this article](https://antman-does-software.com/stop-catching-errors-in-typescript-use-the-either-type-to-make-your-code-predictable) for more information on how `Either` works and its benefits.
174
-
175
- Additionally, `DefiniteEither` is also provided. It is a variation of the aforementioned `Either`, which may or may not have `error` set, but always has `result`.
176
-
177
- ### waitAndRetry
178
-
179
- There is helper function available for writing event-driven assertions in automated tests, which rely on something eventually happening:
180
-
181
- ```ts
182
- import { waitAndRetry } from '@lokalise/node-core'
183
-
184
- const result = await waitAndRetry(
185
- () => {
186
- return someEventEmitter.emittedEvents.length > 0
187
- },
188
- 20, // sleepTime between attempts
189
- 30, // maxRetryCount before timeout
190
- )
191
-
192
- expect(result).toBe(false) // resolves to what the last attempt has returned
193
- expect(someEventEmitter.emittedEvents.length).toBe(1)
194
- ```
195
-
196
- ## Encryption
197
-
198
- - `EncryptionUtility` - small class for encrypting/decrypting using aes-256-gcm. Adapted from: https://github.com/MauriceButler/cryptr
199
-
200
- ## Hashing
201
-
202
- - `HashUtils` - utils for hashing using sha256/sha512 algorithms
203
-
204
- ## Checksum
205
-
206
- - `ChecksumUtils` - utils for insecure hashing using the MD5 algorithm
207
-
208
- ## Streams
209
-
210
- - `StreamUtils` - utils for temporary persisting of streams for length calculation and reuse
211
- - `streamToBuffer` - utility for converting a stream to a buffer
1
+ # node-core 🧬
2
+
3
+ Core libraries for Node.js backend services.
4
+
5
+ - [Default Logging Configuration](#default-logging-configuration)
6
+ - [ConfigScope](#configscope)
7
+ - [Error Handling](#error-handling)
8
+ - [Observability](#observability)
9
+
10
+ See [docs](/docs) for further instructions on how to use.
11
+
12
+ ## Default Logging Configuration
13
+
14
+ The library provides methods to resolve the default logging configuration. Public methods available are:
15
+
16
+ - `resolveLoggerConfiguration()`, which accepts as parameter an `appConfig`, defined by the `logLevel` and the `nodeEnv`. If the environment is production, the output will be logged in JSON format to be friendly with any data storage. Otherwise, the output will be logged with coloring and formatting to be visible for debugging purposes and help developers.
17
+
18
+ The method returns a logger configuration that should be used with `pino` library as in the following example:
19
+
20
+ ```ts
21
+ const loggerConfig = resolveLoggerConfiguration({
22
+ logLevel: 'warn',
23
+ nodeEnv: 'production',
24
+ redact: {
25
+ paths: ['path1', 'path2'],
26
+ },
27
+ })
28
+
29
+ const logger = pino(loggerConfig)
30
+ ```
31
+
32
+ - `resolveMonorepoLoggerConfiguration()`, which accepts as parameter an `appConfig`, defined by the `logLevel` and the `nodeEnv`. It mostly behaves the same as `resolveLoggerConfiguration`, with the exception of execution in `development environments`. Since monorepo services are usually ran concurrently, logs from `stdout` aren't easily accessible. For this reason this logging configuration writes development logs into files.
33
+
34
+ The method returns a logger configuration that should be used with `pino` library as in the following example:
35
+
36
+ ```ts
37
+ const loggerConfig = resolveMonorepoLoggerConfiguration({
38
+ logLevel: 'warn',
39
+ nodeEnv: 'production',
40
+ append: false,
41
+ // targetFile: './logs/service.log' -- optional parameter, you can specify exact path for writing logs
42
+ })
43
+
44
+ const logger = pino(loggerConfig)
45
+ ```
46
+
47
+ ## ConfigScope
48
+
49
+ `ConfigScope` is a class that provides a way to encapsulate a single config source (e. g. `process.env`) and produce a set of values out of it, defining constraints and transformations for them.
50
+
51
+ Once the class is instantiated, you can leverage the following `ConfigScope` methods:
52
+
53
+ ### Configuration Parameters by zod schema
54
+
55
+ - `getBySchema()`, uses zod schema to validate configuration parameter, the returned type is inferred from the schema
56
+ - `param`, the configuration parameter name;
57
+ - `schema`, zod schema to use for parsing and validation;
58
+
59
+ > **Note:** Starting from version 14, the library requires Zod v4 API usage, to continue using Zod v3 API, please use version 13 of the library.
60
+
61
+ ### Mandatory Configuration Parameters
62
+
63
+ - `getMandatory()`, returns the value of a mandatory configuration parameter. If the value is missing, an `InternalError` is thrown. Parameters are:
64
+ - `param`, the configuration parameter name;
65
+ - `getMandatoryInteger()`, returns the value of a mandatory configuration parameter and validates that it is an integer number. If the value is missing or is not an integer, an `InternalError` is thrown. Parameters are:
66
+ - `param`, the configuration parameter name;
67
+ - `getMandatoryNumber()`, returns the value of a mandatory configuration parameter and validates that it is a number. If the value is missing or is not a number, an `InternalError` is thrown. Parameters are:
68
+ - `param`, the configuration parameter name;
69
+ - `getMandatoryOneOf()`, returns the value a mandatory configuration parameter and validates that it is one of the supported values. If the value is missing or is not supported, an `InternalError` is thrown. The method also serves as a type guard, narrowing the type of the passed value down to one of the supported options. Parameters are:
70
+ - `param`, the configuration parameter name;
71
+ - `supportedValues`;
72
+ - `getMandatoryValidatedInteger()`, similar to `getMandatoryInteger()`, but also takes a `validator` in input and will throw an `InternalError` if the number is not valid. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
73
+ - `param`, the configuration parameter name;
74
+ - `validator`;
75
+ - `getMandatoryValidatedNumber()`, similar to `getMandatoryNumber()`, but also takes a `validator` in input and will throw an `InternalError` if the number is not valid. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
76
+ - `param`, the configuration parameter name;
77
+ - `validator`;
78
+ - `getMandatoryTransformed()`, calls `getMandatory()` and returns the result of the `transformer` function applied to the configuration parameter value. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
79
+ - `param`, the configuration parameter name;
80
+ - `transformer`.
81
+
82
+ ### Optional Configuration Parameters
83
+
84
+ - `getOptionalNullable()`, returns the value of an optional configuration parameter. If the value is missing, it is set to the provided default value.Parameters are:
85
+ - `param`, the configuration parameter name;
86
+ - `defaultValue`, which can be nullable;
87
+ - `getOptional()`, similar to `getOptionalNullable()`, but `defaultValue` cannot be nullable. The return value is always a string;
88
+ - `getOptionalNullableInteger()`, returns the value of an optional configuration parameter and validates that it is an integer number. If the value is missing, it is set to the provided default value. If it is not a number, an `InternalError` is thrown. Parameters are:
89
+ - `param`, the configuration parameter name;
90
+ - `defaultValue`, which can be nullable;
91
+ - `getOptionalNullableNumber()`, returns the value of an optional configuration parameter and validates that it is a number. If the value is missing, it is set to the provided default value. If it is not a number, an `InternalError` is thrown. Parameters are:
92
+ - `param`, the configuration parameter name;
93
+ - `defaultValue`, which can be nullable;
94
+ - `getOptionalInteger`, similar to `getOptionalNullableInteger()`, but `defaultValue` cannot be nullable. The return value is always a number;
95
+ - `getOptionalNumber`, similar to `getOptionalNullableNumber()`, but `defaultValue` cannot be nullable. The return value is always a number;
96
+ - `getOptionalValidated()`, similar to `getOptional()`, but also takes a `validator` in input and will throw an `InternalError` if the value is not valid. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
97
+ - `param`, the configuration parameter name;
98
+ - `validator`;
99
+ - `getOptionalValidatedInteger()`, similar to `getOptionalValidated()`, but expects and returns an integer `number` instead. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
100
+ - `param`, the configuration parameter name;
101
+ - `validator`;
102
+ - `getOptionalValidatedNumber()`, similar to `getOptionalValidated()`, but expects and returns `number` instead. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
103
+ - `param`, the configuration parameter name;
104
+ - `validator`;
105
+ - `getOptionalTransformed()`, similar to `getOptional()`, but also takes a `transformer` in input and the result of the `transformer` function applied to the configuration parameter value. See [Validators and Transformers](#validators-and-transformers) for more information. Parameters are:
106
+ - `param`, the configuration parameter name;
107
+ - `defaultValue`,
108
+ - `transformer`;
109
+ - `getOptionalBoolean()`, returns the value of an optional configuration parameter and validates that it is a boolean. It the value is missing, it is assigned the `defaultValue`. If it is not a boolean, an `InternalError` is thrown. Parameters are:
110
+ - `param`, the configuration parameter name;
111
+ - `defaultValue`.
112
+ - `getOptionalOneOf()`, returns the value of an optional configuration parameter, if the value is missing, it falls back to the specified default value, and validates that it is one of the supported values. If the value is not supported, an `InternalError` is thrown. Parameters are:
113
+ - `param`, the configuration parameter name;
114
+ - `defaultValue`
115
+ - `supportedValues`;
116
+
117
+ ### Environment Configuration Parameter
118
+
119
+ - `isProduction()`, returns true if the environment is production;
120
+ - `isDevelopment()`, returns true if the environment is **not** production;
121
+ - `isTest()`, returns true if the environment is test.
122
+
123
+ ---
124
+
125
+ ### Validators and Transformers
126
+
127
+ Ad-hoc validators and transformers can be built leveraging the `EnvValueValidator` and the `EnvValueTransformer` types exposed by the library. Alternatively, the following validators and transformers are already provided out of the box:
128
+
129
+ #### Validators
130
+
131
+ - `createRangeValidator()`, which accepts `greaterOrEqualThan` and `lessOrEqualThan` and validates that a numeric value ranges between those numbers.
132
+
133
+ #### Transformers
134
+
135
+ - `ensureClosingSlashTransformer()`, which accepts a `value` as parameter, that can be a string or nullable, and adds a closing slash if it is missing and the value is defined.
136
+
137
+ ## Error Handling
138
+
139
+ The library provides classes and methods for error handling.
140
+
141
+ ### Global Error Handler
142
+
143
+ Public methods to leverage a global error handler are provided to be used when the process is run outside of the context of the request (e. g. in a queue where no one would catch an error if thrown):
144
+
145
+ - `resolveGlobalErrorLogObject()`, which accepts `err` and optionally `correlationID` as parameters and converts the plain error into a serializable object. If the error is not a built-in `Error` type and doesn't have any message, a fixed string is returned instead;
146
+ - `executeAndHandleGlobalErrors()`, which accepts the `operation` parameter and will return the result of executing such operation. If an error is thrown during the execution of the operation, `resolveGlobalErrorLogObject()` is called to log the error and the process is terminated;
147
+ - `executeAsyncAndHandleGlobalErrors()`, which accepts `operation` and optionally `stopOnError` as parameters and will return the result of executing such operation **asynchronously**. If an error is thrown during the execution of the operation, `resolveGlobalErrorLogObject()` is called to log the error and the process is terminated only if `stopOnError` is `true`. `stopOnError` defaults to `true` if not provided.
148
+
149
+ ### Errors
150
+
151
+ The library exposes classes for the following errors:
152
+
153
+ - `InternalError`, which issues a `500` status code and is not exposed in the global error handler. It expects the following parameters:
154
+ - `message`;
155
+ - `errorCode`;
156
+ - `details` – (optional);
157
+ - `cause` (optional).
158
+ - `PublicNonRecoverableError`, which issues the HTTP status code provided and signals that the user did something wrong, hence the error is returned to the consumer of the API. It expects the following parameters:
159
+ - `message`;
160
+ - `errorCode`;
161
+ - `details` – (optional);
162
+ - `cause` – (optional);
163
+ - `httpStatusCode` – (optional). Defaults to `500`;
164
+
165
+ ### Either
166
+
167
+ The library provides the type `Either` for error handling in the functional paradigm. The two possible values are:
168
+
169
+ - `result` is defined, `error` is undefined;
170
+ - `error` is defined, `result` is undefined.
171
+
172
+ It's up to the caller of the function to handle the received error or throw an error.
173
+
174
+ Read [this article](https://antman-does-software.com/stop-catching-errors-in-typescript-use-the-either-type-to-make-your-code-predictable) for more information on how `Either` works and its benefits.
175
+
176
+ Additionally, `DefiniteEither` is also provided. It is a variation of the aforementioned `Either`, which may or may not have `error` set, but always has `result`.
177
+
178
+ ### waitAndRetry
179
+
180
+ There is helper function available for writing event-driven assertions in automated tests, which rely on something eventually happening:
181
+
182
+ ```ts
183
+ import { waitAndRetry } from '@lokalise/node-core'
184
+
185
+ const result = await waitAndRetry(
186
+ () => {
187
+ return someEventEmitter.emittedEvents.length > 0
188
+ },
189
+ 20, // sleepTime between attempts
190
+ 30, // maxRetryCount before timeout
191
+ )
192
+
193
+ expect(result).toBe(false) // resolves to what the last attempt has returned
194
+ expect(someEventEmitter.emittedEvents.length).toBe(1)
195
+ ```
196
+
197
+ ## Encryption
198
+
199
+ - `EncryptionUtility` - small class for encrypting/decrypting using aes-256-gcm. Adapted from: https://github.com/MauriceButler/cryptr
200
+
201
+ ## Hashing
202
+
203
+ - `HashUtils` - utils for hashing using sha256/sha512 algorithms
204
+
205
+ ## Checksum
206
+
207
+ - `ChecksumUtils` - utils for insecure hashing using the MD5 algorithm
208
+
209
+ ## Streams
210
+
211
+ - `StreamUtils` - utils for temporary persisting of streams for length calculation and reuse
212
+ - `streamToBuffer` - utility for converting a stream to a buffer
213
+
214
+ ## Observability
215
+
216
+ The library provides utilities for transaction observability management through the `TransactionObservabilityManager` interface.
217
+
218
+ ### TransactionObservabilityManager
219
+
220
+ An interface for tracking background transactions with the following methods:
221
+
222
+ - `start(transactionName, uniqueTransactionKey)` - Creates and starts a background transaction
223
+ - `startWithGroup(transactionName, uniqueTransactionKey, transactionGroup)` - Creates and starts a background transaction related to a specified group
224
+ - `stop(uniqueTransactionKey, wasSuccessful?)` - Ends the transaction
225
+ - `addCustomAttributes(uniqueTransactionKey, atts)` - Adds custom attributes to the current transaction
226
+
227
+ ### MultiTransactionObservabilityManager
228
+
229
+ Groups multiple `TransactionObservabilityManager` instances into one to facilitate tracking transactions across multiple observability tools.
230
+
231
+ ```ts
232
+ import { MultiTransactionObservabilityManager } from '@lokalise/node-core'
233
+
234
+ const multiManager = new MultiTransactionObservabilityManager([
235
+ newRelicManager,
236
+ datadogManager,
237
+ ])
238
+
239
+ multiManager.start('processOrder', 'order-123')
240
+ ```
241
+
242
+ ### NoopObservabilityManager
243
+
244
+ A no-operation implementation of `TransactionObservabilityManager`. All methods are implemented but do nothing. Use this when you need to satisfy a `TransactionObservabilityManager` dependency but don't want any actual observability tracking to occur.
245
+
246
+ ```ts
247
+ import { NoopObservabilityManager } from '@lokalise/node-core'
248
+
249
+ const noopManager = new NoopObservabilityManager()
250
+ // Pass to any component requiring a TransactionObservabilityManager
251
+ const service = new MyService({ observabilityManager: noopManager })
252
+ ```
package/dist/index.cjs CHANGED
@@ -41,6 +41,7 @@ __export(index_exports, {
41
41
  HashEncoding: () => HashEncoding,
42
42
  InternalError: () => InternalError,
43
43
  MultiTransactionObservabilityManager: () => MultiTransactionObservabilityManager,
44
+ NoopObservabilityManager: () => NoopObservabilityManager,
44
45
  PublicNonRecoverableError: () => PublicNonRecoverableError,
45
46
  RequestValidationError: () => RequestValidationError,
46
47
  callChunked: () => callChunked,
@@ -1016,6 +1017,39 @@ var MultiTransactionObservabilityManager = class {
1016
1017
  }
1017
1018
  };
1018
1019
 
1020
+ // src/observability/NoopObservabilityManager.ts
1021
+ var NoopObservabilityManager = class {
1022
+ /**
1023
+ * No-op implementation of start. Does nothing.
1024
+ * @param _transactionName - Ignored
1025
+ * @param _uniqueTransactionKey - Ignored
1026
+ */
1027
+ start(_transactionName, _uniqueTransactionKey) {
1028
+ }
1029
+ /**
1030
+ * No-op implementation of startWithGroup. Does nothing.
1031
+ * @param _transactionName - Ignored
1032
+ * @param _uniqueTransactionKey - Ignored
1033
+ * @param _transactionGroup - Ignored
1034
+ */
1035
+ startWithGroup(_transactionName, _uniqueTransactionKey, _transactionGroup) {
1036
+ }
1037
+ /**
1038
+ * No-op implementation of stop. Does nothing.
1039
+ * @param _uniqueTransactionKey - Ignored
1040
+ * @param _wasSuccessful - Ignored
1041
+ */
1042
+ stop(_uniqueTransactionKey, _wasSuccessful) {
1043
+ }
1044
+ /**
1045
+ * No-op implementation of addCustomAttributes. Does nothing.
1046
+ * @param _uniqueTransactionKey - Ignored
1047
+ * @param _atts - Ignored
1048
+ */
1049
+ addCustomAttributes(_uniqueTransactionKey, _atts) {
1050
+ }
1051
+ };
1052
+
1019
1053
  // src/utils/checksumUtils.ts
1020
1054
  var import_node_crypto2 = require("crypto");
1021
1055
  var HASH_ALGORITHM = "md5";
@@ -1122,6 +1156,7 @@ async function streamToBuffer(stream) {
1122
1156
  HashEncoding,
1123
1157
  InternalError,
1124
1158
  MultiTransactionObservabilityManager,
1159
+ NoopObservabilityManager,
1125
1160
  PublicNonRecoverableError,
1126
1161
  RequestValidationError,
1127
1162
  callChunked,