@lokalise/node-core 9.9.0 → 10.0.0-RC1

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/dist/index.mjs ADDED
@@ -0,0 +1,848 @@
1
+ import { Client } from 'undici';
2
+ import { sendWithRetry, NO_RETRY_CONFIG, isRequestResult } from 'undici-retry';
3
+ import { types } from 'node:util';
4
+ import { pino, levels, stdSerializers } from 'pino';
5
+ import { constants } from 'node:http2';
6
+
7
+ var __defProp$3 = Object.defineProperty;
8
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __publicField$3 = (obj, key, value) => {
10
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
11
+ return value;
12
+ };
13
+ class InternalError extends Error {
14
+ constructor(params) {
15
+ super(params.message);
16
+ __publicField$3(this, "details");
17
+ __publicField$3(this, "errorCode");
18
+ this.name = "InternalError";
19
+ this.details = params.details;
20
+ this.errorCode = params.errorCode;
21
+ }
22
+ }
23
+
24
+ var __defProp$2 = Object.defineProperty;
25
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
26
+ var __publicField$2 = (obj, key, value) => {
27
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+ return value;
29
+ };
30
+ class ResponseStatusError extends InternalError {
31
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
+ constructor(requestResult, requestLabel = "N/A") {
33
+ super({
34
+ message: `Response status code ${requestResult.statusCode}`,
35
+ details: {
36
+ requestLabel,
37
+ response: {
38
+ statusCode: requestResult.statusCode,
39
+ body: requestResult.body
40
+ }
41
+ },
42
+ errorCode: "REQUEST_ERROR"
43
+ });
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ __publicField$2(this, "response");
46
+ __publicField$2(this, "isResponseStatusError", true);
47
+ this.response = requestResult;
48
+ this.name = "ResponseStatusError";
49
+ }
50
+ }
51
+
52
+ function copyWithoutUndefined(originalValue) {
53
+ return Object.keys(originalValue).reduce(
54
+ (acc, key) => {
55
+ if (originalValue[key] !== void 0) {
56
+ acc[key] = originalValue[key];
57
+ }
58
+ return acc;
59
+ },
60
+ {}
61
+ );
62
+ }
63
+ function pick(source, propNames) {
64
+ const result = {};
65
+ let idx = 0;
66
+ while (idx < propNames.length) {
67
+ if (propNames[idx] in source) {
68
+ result[propNames[idx]] = source[propNames[idx]];
69
+ }
70
+ idx += 1;
71
+ }
72
+ return result;
73
+ }
74
+ function pickWithoutUndefined(source, propNames) {
75
+ const result = {};
76
+ let idx = 0;
77
+ while (idx < propNames.length) {
78
+ if (propNames[idx] in source && source[propNames[idx]] !== void 0) {
79
+ result[propNames[idx]] = source[propNames[idx]];
80
+ }
81
+ idx += 1;
82
+ }
83
+ return result;
84
+ }
85
+ function isEmptyObject(params) {
86
+ for (const key in params) {
87
+ if (Object.hasOwn(params, key) && params[key] !== void 0) {
88
+ return false;
89
+ }
90
+ }
91
+ return true;
92
+ }
93
+ function groupBy(array, selector) {
94
+ return array.reduce(
95
+ (acc, item) => {
96
+ const key = item[selector];
97
+ if (key === void 0 || key === null) {
98
+ return acc;
99
+ }
100
+ if (!acc[key]) {
101
+ acc[key] = [];
102
+ }
103
+ acc[key].push(item);
104
+ return acc;
105
+ },
106
+ {}
107
+ );
108
+ }
109
+ function groupByUnique(array, selector) {
110
+ return array.reduce(
111
+ (acc, item) => {
112
+ const key = item[selector];
113
+ if (key === void 0 || key === null) {
114
+ return acc;
115
+ }
116
+ if (acc[key] !== void 0) {
117
+ throw new InternalError({
118
+ message: `Duplicated item for selector ${selector.toString()} with value ${key.toString()}`,
119
+ errorCode: "DUPLICATED_ITEM",
120
+ details: { selector, value: key }
121
+ });
122
+ }
123
+ acc[key] = item;
124
+ return acc;
125
+ },
126
+ {}
127
+ );
128
+ }
129
+ function convertDateFieldsToIsoString(object) {
130
+ if (Array.isArray(object)) {
131
+ return object.map(convertDateFieldsToIsoStringAux);
132
+ }
133
+ return Object.entries(object).reduce((result, [key, value]) => {
134
+ result[key] = convertDateFieldsToIsoStringAux(value);
135
+ return result;
136
+ }, {});
137
+ }
138
+ function convertDateFieldsToIsoStringAux(item) {
139
+ if (item instanceof Date) {
140
+ return item.toISOString();
141
+ } else if (item && typeof item === "object") {
142
+ return convertDateFieldsToIsoString(item);
143
+ } else {
144
+ return item;
145
+ }
146
+ }
147
+ function deepClone(object) {
148
+ if (object === void 0 || object === null) {
149
+ return object;
150
+ }
151
+ return structuredClone(object);
152
+ }
153
+
154
+ const DEFAULT_OPTIONS = {
155
+ validateResponse: true,
156
+ throwOnError: true,
157
+ timeout: 3e4
158
+ };
159
+ const defaultClientOptions = {
160
+ keepAliveMaxTimeout: 3e5,
161
+ keepAliveTimeout: 4e3
162
+ };
163
+ async function sendGet(client, path, options = {}) {
164
+ const result = await sendWithRetry(
165
+ client,
166
+ {
167
+ ...DEFAULT_OPTIONS,
168
+ path,
169
+ method: "GET",
170
+ query: options.query,
171
+ headers: copyWithoutUndefined({
172
+ "x-request-id": options.reqContext?.reqId,
173
+ ...options.headers
174
+ }),
175
+ reset: options.disableKeepAlive ?? false,
176
+ bodyTimeout: options.timeout,
177
+ throwOnError: false
178
+ },
179
+ resolveRetryConfig(options),
180
+ resolveRequestConfig(options)
181
+ );
182
+ return resolveResult(
183
+ result,
184
+ options.throwOnError ?? DEFAULT_OPTIONS.throwOnError,
185
+ options.validateResponse ?? DEFAULT_OPTIONS.validateResponse,
186
+ options.responseSchema,
187
+ options.requestLabel
188
+ );
189
+ }
190
+ async function sendDelete(client, path, options = {}) {
191
+ const result = await sendWithRetry(
192
+ client,
193
+ {
194
+ ...DEFAULT_OPTIONS,
195
+ path,
196
+ method: "DELETE",
197
+ query: options.query,
198
+ headers: copyWithoutUndefined({
199
+ "x-request-id": options.reqContext?.reqId,
200
+ ...options.headers
201
+ }),
202
+ reset: options.disableKeepAlive ?? false,
203
+ bodyTimeout: options.timeout,
204
+ throwOnError: false
205
+ },
206
+ resolveRetryConfig(options),
207
+ resolveRequestConfig(options)
208
+ );
209
+ return resolveResult(
210
+ result,
211
+ options.throwOnError ?? DEFAULT_OPTIONS.throwOnError,
212
+ options.validateResponse ?? DEFAULT_OPTIONS.validateResponse,
213
+ options.responseSchema
214
+ );
215
+ }
216
+ async function sendPost(client, path, body, options = {}) {
217
+ const result = await sendWithRetry(
218
+ client,
219
+ {
220
+ ...DEFAULT_OPTIONS,
221
+ path,
222
+ method: "POST",
223
+ body: body ? JSON.stringify(body) : void 0,
224
+ query: options.query,
225
+ headers: copyWithoutUndefined({
226
+ "x-request-id": options.reqContext?.reqId,
227
+ ...options.headers
228
+ }),
229
+ reset: options.disableKeepAlive ?? false,
230
+ bodyTimeout: options.timeout,
231
+ throwOnError: false
232
+ },
233
+ resolveRetryConfig(options),
234
+ resolveRequestConfig(options)
235
+ );
236
+ return resolveResult(
237
+ result,
238
+ options.throwOnError ?? DEFAULT_OPTIONS.throwOnError,
239
+ options.validateResponse ?? DEFAULT_OPTIONS.validateResponse,
240
+ options.responseSchema
241
+ );
242
+ }
243
+ async function sendPostBinary(client, path, body, options = {}) {
244
+ const result = await sendWithRetry(
245
+ client,
246
+ {
247
+ ...DEFAULT_OPTIONS,
248
+ path,
249
+ method: "POST",
250
+ body,
251
+ query: options.query,
252
+ headers: copyWithoutUndefined({
253
+ "x-request-id": options.reqContext?.reqId,
254
+ ...options.headers
255
+ }),
256
+ reset: options.disableKeepAlive ?? false,
257
+ bodyTimeout: options.timeout,
258
+ throwOnError: false
259
+ },
260
+ resolveRetryConfig(options),
261
+ resolveRequestConfig(options)
262
+ );
263
+ return resolveResult(
264
+ result,
265
+ options.throwOnError ?? DEFAULT_OPTIONS.throwOnError,
266
+ options.validateResponse ?? DEFAULT_OPTIONS.validateResponse,
267
+ options.responseSchema
268
+ );
269
+ }
270
+ async function sendPut(client, path, body, options = {}) {
271
+ const result = await sendWithRetry(
272
+ client,
273
+ {
274
+ ...DEFAULT_OPTIONS,
275
+ path,
276
+ method: "PUT",
277
+ body: body ? JSON.stringify(body) : void 0,
278
+ query: options.query,
279
+ headers: copyWithoutUndefined({
280
+ "x-request-id": options.reqContext?.reqId,
281
+ ...options.headers
282
+ }),
283
+ reset: options.disableKeepAlive ?? false,
284
+ bodyTimeout: options.timeout,
285
+ throwOnError: false
286
+ },
287
+ resolveRetryConfig(options),
288
+ resolveRequestConfig(options)
289
+ );
290
+ return resolveResult(
291
+ result,
292
+ options.throwOnError ?? DEFAULT_OPTIONS.throwOnError,
293
+ options.validateResponse ?? DEFAULT_OPTIONS.validateResponse,
294
+ options.responseSchema
295
+ );
296
+ }
297
+ async function sendPutBinary(client, path, body, options = {}) {
298
+ const result = await sendWithRetry(
299
+ client,
300
+ {
301
+ ...DEFAULT_OPTIONS,
302
+ path,
303
+ method: "PUT",
304
+ body,
305
+ query: options.query,
306
+ headers: copyWithoutUndefined({
307
+ "x-request-id": options.reqContext?.reqId,
308
+ ...options.headers
309
+ }),
310
+ reset: options.disableKeepAlive ?? false,
311
+ bodyTimeout: options.timeout,
312
+ throwOnError: false
313
+ },
314
+ resolveRetryConfig(options),
315
+ resolveRequestConfig(options)
316
+ );
317
+ return resolveResult(
318
+ result,
319
+ options.throwOnError ?? DEFAULT_OPTIONS.throwOnError,
320
+ options.validateResponse ?? DEFAULT_OPTIONS.validateResponse,
321
+ options.responseSchema
322
+ );
323
+ }
324
+ async function sendPatch(client, path, body, options = {}) {
325
+ const result = await sendWithRetry(
326
+ client,
327
+ {
328
+ ...DEFAULT_OPTIONS,
329
+ path,
330
+ method: "PATCH",
331
+ body: body ? JSON.stringify(body) : void 0,
332
+ query: options.query,
333
+ headers: copyWithoutUndefined({
334
+ "x-request-id": options.reqContext?.reqId,
335
+ ...options.headers
336
+ }),
337
+ reset: options.disableKeepAlive ?? false,
338
+ bodyTimeout: options.timeout,
339
+ throwOnError: false
340
+ },
341
+ resolveRetryConfig(options),
342
+ resolveRequestConfig(options)
343
+ );
344
+ return resolveResult(
345
+ result,
346
+ options.throwOnError ?? DEFAULT_OPTIONS.throwOnError,
347
+ options.validateResponse ?? DEFAULT_OPTIONS.validateResponse,
348
+ options.responseSchema
349
+ );
350
+ }
351
+ function resolveRequestConfig(options) {
352
+ return {
353
+ safeParseJson: options.safeParseJson ?? false,
354
+ blobBody: options.blobResponseBody ?? false,
355
+ throwOnInternalError: false,
356
+ requestLabel: options.requestLabel
357
+ };
358
+ }
359
+ function resolveRetryConfig(options) {
360
+ return options.retryConfig ?? NO_RETRY_CONFIG;
361
+ }
362
+ function buildClient(baseUrl, clientOptions) {
363
+ const newClient = new Client(baseUrl, {
364
+ ...defaultClientOptions,
365
+ ...clientOptions
366
+ });
367
+ return newClient;
368
+ }
369
+ function resolveResult(requestResult, throwOnError, validateResponse, validationSchema, requestLabel) {
370
+ if (requestResult.error && throwOnError) {
371
+ if (isRequestResult(requestResult.error)) {
372
+ throw new ResponseStatusError(requestResult.error, requestLabel);
373
+ }
374
+ throw requestResult.error;
375
+ }
376
+ if (requestResult.result && validateResponse && validationSchema) {
377
+ requestResult.result.body = validationSchema.parse(requestResult.result.body);
378
+ }
379
+ return requestResult;
380
+ }
381
+ const httpClient = {
382
+ get: sendGet,
383
+ post: sendPost,
384
+ put: sendPut,
385
+ patch: sendPatch,
386
+ del: sendDelete
387
+ };
388
+
389
+ var __defProp$1 = Object.defineProperty;
390
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
391
+ var __publicField$1 = (obj, key, value) => {
392
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
393
+ return value;
394
+ };
395
+ class PublicNonRecoverableError extends Error {
396
+ constructor(params) {
397
+ super(params.message);
398
+ __publicField$1(this, "details");
399
+ __publicField$1(this, "errorCode");
400
+ __publicField$1(this, "httpStatusCode");
401
+ this.name = "PublicNonRecoverableError";
402
+ this.details = params.details;
403
+ this.errorCode = params.errorCode;
404
+ this.httpStatusCode = params.httpStatusCode ?? 500;
405
+ }
406
+ }
407
+
408
+ function isResponseStatusError(entity) {
409
+ return "isResponseStatusError" in entity;
410
+ }
411
+
412
+ var __defProp = Object.defineProperty;
413
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
414
+ var __publicField = (obj, key, value) => {
415
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
416
+ return value;
417
+ };
418
+ class ConfigScope {
419
+ constructor(envOverride) {
420
+ __publicField(this, "env");
421
+ this.env = envOverride ?? { ...process.env };
422
+ }
423
+ updateEnv() {
424
+ this.env = { ...process.env };
425
+ }
426
+ getMandatoryInteger(param) {
427
+ const rawValue = this.env[param];
428
+ if (!rawValue) {
429
+ throw new InternalError({
430
+ message: `Missing mandatory configuration parameter: ${param}`,
431
+ errorCode: "CONFIGURATION_ERROR"
432
+ });
433
+ }
434
+ return validateNumber(
435
+ Number.parseInt(rawValue),
436
+ `Configuration parameter ${param}\` must be a number, but was ${rawValue}`
437
+ );
438
+ }
439
+ getMandatory(param) {
440
+ const result = this.env[param];
441
+ if (!result) {
442
+ throw new InternalError({
443
+ message: `Missing mandatory configuration parameter: ${param}`,
444
+ errorCode: "CONFIGURATION_ERROR"
445
+ });
446
+ }
447
+ return result;
448
+ }
449
+ getMandatoryOneOf(param, supportedValues) {
450
+ const result = this.getMandatory(param);
451
+ return validateOneOf(
452
+ result,
453
+ supportedValues,
454
+ `Unsupported ${param}: ${result}. Supported values: ${supportedValues.toString()}`
455
+ );
456
+ }
457
+ getMandatoryValidatedInteger(param, validator) {
458
+ const value = this.getMandatoryInteger(param);
459
+ if (!validator(value)) {
460
+ throw new InternalError({
461
+ message: `Value ${value} is invalid for parameter ${param}`,
462
+ errorCode: "CONFIGURATION_ERROR"
463
+ });
464
+ }
465
+ return value;
466
+ }
467
+ getOptionalNullable(param, defaultValue) {
468
+ return this.env[param] || defaultValue;
469
+ }
470
+ getOptional(param, defaultValue) {
471
+ return this.env[param] || defaultValue;
472
+ }
473
+ getOptionalInteger(param, defaultValue) {
474
+ const rawValue = this.env[param];
475
+ if (!rawValue) {
476
+ return defaultValue;
477
+ }
478
+ return validateNumber(
479
+ Number.parseInt(rawValue),
480
+ `Configuration parameter ${param}\` must be a number, but was ${rawValue}`
481
+ );
482
+ }
483
+ getOptionalNullableInteger(param, defaultValue) {
484
+ const rawValue = this.env[param];
485
+ if (!rawValue) {
486
+ return defaultValue;
487
+ }
488
+ return validateNumber(
489
+ Number.parseInt(rawValue),
490
+ `Configuration parameter ${param}\` must be a number, but was ${rawValue}`
491
+ );
492
+ }
493
+ getOptionalOneOf(param, defaultValue, supportedValues) {
494
+ const result = this.getOptional(param, defaultValue);
495
+ return validateOneOf(
496
+ result,
497
+ supportedValues,
498
+ `Unsupported ${param}: ${result}. Supported values: ${supportedValues.toString()}`
499
+ );
500
+ }
501
+ getOptionalValidated(param, defaultValue, validator) {
502
+ const value = this.env[param] || defaultValue;
503
+ if (!validator(value)) {
504
+ throw new InternalError({
505
+ message: `Value ${value} is invalid for parameter ${param}`,
506
+ errorCode: "CONFIGURATION_ERROR"
507
+ });
508
+ }
509
+ return value;
510
+ }
511
+ getOptionalValidatedInteger(param, defaultValue, validator) {
512
+ const value = this.getOptionalInteger(param, defaultValue);
513
+ if (!validator(value)) {
514
+ throw new InternalError({
515
+ message: `Value ${value} is invalid for parameter ${param}`,
516
+ errorCode: "CONFIGURATION_ERROR"
517
+ });
518
+ }
519
+ return value;
520
+ }
521
+ getOptionalTransformed(param, defaultValue, transformer) {
522
+ const value = this.env[param] || defaultValue;
523
+ return transformer(value);
524
+ }
525
+ getOptionalNullableTransformed(param, defaultValue, transformer) {
526
+ const value = this.env[param] || defaultValue;
527
+ return transformer(value);
528
+ }
529
+ getMandatoryTransformed(param, transformer) {
530
+ const value = this.getMandatory(param);
531
+ return transformer(value);
532
+ }
533
+ getOptionalBoolean(param, defaultValue) {
534
+ const rawValue = this.env[param]?.toLowerCase();
535
+ if (rawValue === void 0 || rawValue === "") {
536
+ return defaultValue;
537
+ }
538
+ validateOneOf(rawValue, ["true", "false"]);
539
+ return rawValue === "true";
540
+ }
541
+ getMandatoryJsonObject(param, schema) {
542
+ const rawValue = this.getMandatory(param);
543
+ return this.validateSchema(
544
+ JSON.parse(rawValue),
545
+ schema,
546
+ `Configuration parameter ${param} must be a valid JSON meeting the given schema, but was ${rawValue}`
547
+ );
548
+ }
549
+ getOptionalNullableJsonObject(param, schema, defaultValue) {
550
+ const rawValue = this.getOptionalNullable(param, void 0);
551
+ if (!rawValue) {
552
+ return defaultValue;
553
+ }
554
+ return this.validateSchema(
555
+ JSON.parse(rawValue),
556
+ schema,
557
+ `Configuration parameter ${param} must be a valid JSON meeting the given schema, but was ${rawValue}`
558
+ );
559
+ }
560
+ getOptionalJsonObject(param, schema, defaultValue) {
561
+ return this.getOptionalNullableJsonObject(param, schema, defaultValue);
562
+ }
563
+ isProduction() {
564
+ return this.env.NODE_ENV === "production";
565
+ }
566
+ isDevelopment() {
567
+ return this.env.NODE_ENV !== "production";
568
+ }
569
+ isTest() {
570
+ return this.env.NODE_ENV === "test";
571
+ }
572
+ validateSchema(value, schema, errorMessage) {
573
+ const parsedValue = schema.safeParse(value);
574
+ if (!parsedValue.success) {
575
+ throw new InternalError({
576
+ message: errorMessage,
577
+ errorCode: "CONFIGURATION_ERROR",
578
+ details: parsedValue.error
579
+ });
580
+ }
581
+ return parsedValue.data;
582
+ }
583
+ }
584
+ function validateOneOf(validatedEntity, expectedOneOfEntities, errorText) {
585
+ if (!expectedOneOfEntities.includes(validatedEntity)) {
586
+ throw new InternalError({
587
+ message: errorText || // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
588
+ `Validated entity ${validatedEntity} is not one of: ${expectedOneOfEntities.toString()}`,
589
+ errorCode: "CONFIGURATION_ERROR"
590
+ });
591
+ }
592
+ return validatedEntity;
593
+ }
594
+ function validateNumber(validatedObject, errorText) {
595
+ if (!Number.isFinite(validatedObject)) {
596
+ throw new InternalError({
597
+ message: errorText,
598
+ errorCode: "CONFIGURATION_ERROR"
599
+ });
600
+ }
601
+ return validatedObject;
602
+ }
603
+
604
+ const ensureClosingSlashTransformer = (value) => {
605
+ if (!value) {
606
+ return "";
607
+ }
608
+ const lastChar = value.at(-1);
609
+ if (lastChar !== "/") {
610
+ return `${value}/`;
611
+ }
612
+ return value;
613
+ };
614
+
615
+ const createRangeValidator = (greaterOrEqualThan, lessOrEqualThan) => {
616
+ return (value) => {
617
+ return value >= greaterOrEqualThan && value <= lessOrEqualThan;
618
+ };
619
+ };
620
+
621
+ const isFailure = (e) => {
622
+ return e.error !== void 0;
623
+ };
624
+ const isSuccess = (e) => {
625
+ return e.result !== void 0;
626
+ };
627
+ const failure = (error) => ({ error });
628
+ const success = (result) => ({ result });
629
+
630
+ function chunk(array, chunkSize) {
631
+ const length = array.length;
632
+ if (!length || chunkSize < 1) {
633
+ return [];
634
+ }
635
+ let index = 0;
636
+ let resIndex = 0;
637
+ const result = new Array(Math.ceil(length / chunkSize));
638
+ while (index < length) {
639
+ result[resIndex++] = array.slice(index, index += chunkSize);
640
+ }
641
+ return result;
642
+ }
643
+ async function callChunked(chunkSize, array, processFn) {
644
+ for (let i = 0; i < array.length; i += chunkSize) {
645
+ const arrayChunk = array.slice(i, i + chunkSize);
646
+ await processFn(arrayChunk);
647
+ }
648
+ }
649
+ function removeNullish(array) {
650
+ return array.filter((e) => e !== void 0 && e !== null);
651
+ }
652
+ function removeFalsy(array) {
653
+ return array.filter((e) => e);
654
+ }
655
+
656
+ function hasMessage(maybe) {
657
+ return isObject(maybe) && typeof maybe.message === "string";
658
+ }
659
+ function isObject(maybeObject) {
660
+ return typeof maybeObject === "object" && maybeObject !== null;
661
+ }
662
+ function isStandardizedError(error) {
663
+ return isObject(error) && typeof error.code === "string" && typeof error.message === "string";
664
+ }
665
+ function isInternalError(error) {
666
+ return isObject(error) && error.name === "InternalError";
667
+ }
668
+ function isPublicNonRecoverableError(error) {
669
+ return isObject(error) && error.name === "PublicNonRecoverableError";
670
+ }
671
+
672
+ function resolveMonorepoLoggerConfiguration(appConfig) {
673
+ if (appConfig.nodeEnv !== "development") {
674
+ return resolveLoggerConfiguration(appConfig);
675
+ }
676
+ return {
677
+ level: appConfig.logLevel,
678
+ formatters: {
679
+ level: (label) => {
680
+ return { level: label };
681
+ }
682
+ },
683
+ transport: {
684
+ target: "pino/file",
685
+ options: {
686
+ destination: appConfig.targetFile ?? "./service.log",
687
+ mkdir: true,
688
+ append: appConfig.append ?? false
689
+ }
690
+ }
691
+ };
692
+ }
693
+ function resolveLoggerConfiguration(appConfig) {
694
+ const config = {
695
+ level: appConfig.logLevel,
696
+ formatters: {
697
+ level: (label) => {
698
+ return { level: label };
699
+ }
700
+ },
701
+ base: appConfig.base
702
+ };
703
+ if (appConfig.nodeEnv !== "production") {
704
+ config.transport = {
705
+ target: "pino-pretty",
706
+ options: {
707
+ colorize: true,
708
+ translateTime: "SYS:standard",
709
+ ignore: "hostname,pid"
710
+ }
711
+ };
712
+ }
713
+ return config;
714
+ }
715
+
716
+ const globalLogger = pino({
717
+ formatters: {
718
+ level: (label, numericLevel) => {
719
+ const level = levels.labels[numericLevel] || "unknown";
720
+ return { level };
721
+ }
722
+ }
723
+ });
724
+ function resolveGlobalErrorLogObject(err, correlationID) {
725
+ if (types.isNativeError(err)) {
726
+ return {
727
+ ...stdSerializers.err(err),
728
+ correlationID
729
+ };
730
+ }
731
+ if (hasMessage(err)) {
732
+ return correlationID ? `${err.message} (${correlationID})` : err.message;
733
+ }
734
+ return "Unknown error";
735
+ }
736
+ function logGlobalErrorLogObject(logObject) {
737
+ if (typeof logObject === "string") {
738
+ globalLogger.error(`Global error: ${logObject}`);
739
+ } else {
740
+ globalLogger.error(logObject, logObject.message);
741
+ }
742
+ }
743
+ function executeAndHandleGlobalErrors(operation) {
744
+ try {
745
+ const result = operation();
746
+ return result;
747
+ } catch (err) {
748
+ const logObject = resolveGlobalErrorLogObject(err);
749
+ logGlobalErrorLogObject(logObject);
750
+ process.exit(1);
751
+ }
752
+ }
753
+ async function executeAsyncAndHandleGlobalErrors(operation, stopOnError = true) {
754
+ try {
755
+ const result = await operation();
756
+ return result;
757
+ } catch (err) {
758
+ const logObject = resolveGlobalErrorLogObject(err);
759
+ logGlobalErrorLogObject(logObject);
760
+ if (stopOnError) {
761
+ process.exit(1);
762
+ }
763
+ }
764
+ }
765
+ async function executeSettleAllAndHandleGlobalErrors(promises, stopOnError = true) {
766
+ const result = await Promise.allSettled(promises);
767
+ let errorsHappened;
768
+ for (const entry of result) {
769
+ if (entry.status === "rejected") {
770
+ const logObject = resolveGlobalErrorLogObject(entry.reason);
771
+ logGlobalErrorLogObject(logObject);
772
+ errorsHappened = true;
773
+ }
774
+ }
775
+ if (stopOnError && errorsHappened) {
776
+ process.exit(1);
777
+ }
778
+ return result;
779
+ }
780
+
781
+ class RequestValidationError extends PublicNonRecoverableError {
782
+ constructor(errors) {
783
+ super({
784
+ message: "Invalid params",
785
+ errorCode: "VALIDATION_ERROR",
786
+ httpStatusCode: constants.HTTP_STATUS_BAD_REQUEST,
787
+ details: {
788
+ error: errors
789
+ }
790
+ });
791
+ }
792
+ }
793
+ class AccessDeniedError extends PublicNonRecoverableError {
794
+ constructor(params) {
795
+ super({
796
+ message: params.message,
797
+ errorCode: "ACCESS_DENIED",
798
+ httpStatusCode: constants.HTTP_STATUS_FORBIDDEN,
799
+ details: params.details
800
+ });
801
+ }
802
+ }
803
+ class EntityNotFoundError extends PublicNonRecoverableError {
804
+ constructor(params) {
805
+ super({
806
+ message: params.message,
807
+ errorCode: "ENTITY_NOT_FOUND",
808
+ httpStatusCode: constants.HTTP_STATUS_NOT_FOUND,
809
+ details: params.details
810
+ });
811
+ }
812
+ }
813
+ class AuthFailedError extends PublicNonRecoverableError {
814
+ constructor(params = {}) {
815
+ super({
816
+ message: params.message ?? "Authentication failed",
817
+ errorCode: "AUTH_FAILED",
818
+ httpStatusCode: constants.HTTP_STATUS_UNAUTHORIZED,
819
+ details: params.details
820
+ });
821
+ }
822
+ }
823
+
824
+ const waitAndRetry = async (predicateFn, sleepTime = 20, maxRetryCount = 15) => {
825
+ return new Promise((resolve, reject) => {
826
+ let retryCount = 0;
827
+ function performCheck() {
828
+ if (maxRetryCount !== 0 && retryCount > maxRetryCount) {
829
+ resolve(predicateFn());
830
+ }
831
+ Promise.resolve().then(() => {
832
+ return predicateFn();
833
+ }).then((result) => {
834
+ if (result) {
835
+ resolve(result);
836
+ } else {
837
+ retryCount++;
838
+ setTimeout(performCheck, sleepTime);
839
+ }
840
+ }).catch((err) => {
841
+ reject(err);
842
+ });
843
+ }
844
+ performCheck();
845
+ });
846
+ };
847
+
848
+ export { AccessDeniedError, AuthFailedError, ConfigScope, EntityNotFoundError, InternalError, PublicNonRecoverableError, RequestValidationError, ResponseStatusError, buildClient, callChunked, chunk, convertDateFieldsToIsoString, copyWithoutUndefined, createRangeValidator, deepClone, ensureClosingSlashTransformer, executeAndHandleGlobalErrors, executeAsyncAndHandleGlobalErrors, executeSettleAllAndHandleGlobalErrors, failure, globalLogger, groupBy, groupByUnique, hasMessage, httpClient, isEmptyObject, isFailure, isInternalError, isObject, isPublicNonRecoverableError, isResponseStatusError, isStandardizedError, isSuccess, pick, pickWithoutUndefined, removeFalsy, removeNullish, resolveGlobalErrorLogObject, resolveLoggerConfiguration, resolveMonorepoLoggerConfiguration, sendDelete, sendGet, sendPatch, sendPost, sendPostBinary, sendPut, sendPutBinary, success, waitAndRetry };