fockeror 0.2.1 → 0.3.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.
@@ -6,6 +6,11 @@
6
6
  * // Найдёт: ${{ username }}
7
7
  */
8
8
  export declare const PLACEHOLDER_PATTERN: RegExp;
9
+ export declare const OFFSETS: {
10
+ readonly START: number;
11
+ /** negative (`-length`) */
12
+ readonly END: number;
13
+ };
9
14
  /** Статус HTTP по умолчанию (500 Internal Server Error). */
10
15
  export declare const DEFAULT_HTTP_STATUS: 500;
11
16
  /** Регулярное выражение для экранирования специальных символов при создании RegExp из ключа. */
package/dist/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CLEAN_REGEX_REPLACER = exports.CLEAN_SEARCH_REGEX = exports.DEFAULT_HTTP_STATUS = exports.PLACEHOLDER_PATTERN = void 0;
3
+ exports.CLEAN_REGEX_REPLACER = exports.CLEAN_SEARCH_REGEX = exports.DEFAULT_HTTP_STATUS = exports.OFFSETS = exports.PLACEHOLDER_PATTERN = void 0;
4
4
  /**
5
5
  * Регулярное выражение для поиска плейсхолдеров вида `${{ key }}`.
6
6
  * Допускает только один пробел внутри скобок.
@@ -9,6 +9,11 @@ exports.CLEAN_REGEX_REPLACER = exports.CLEAN_SEARCH_REGEX = exports.DEFAULT_HTTP
9
9
  * // Найдёт: ${{ username }}
10
10
  */
11
11
  exports.PLACEHOLDER_PATTERN = /\$\{\{\s{1}([^}\s]+)\s{1}\}\}/g;
12
+ exports.OFFSETS = {
13
+ START: "${{ ".length,
14
+ /** negative (`-length`) */
15
+ END: -" }}".length,
16
+ };
12
17
  /** Статус HTTP по умолчанию (500 Internal Server Error). */
13
18
  exports.DEFAULT_HTTP_STATUS = 500;
14
19
  /** Регулярное выражение для экранирования специальных символов при создании RegExp из ключа. */
package/dist/factory.d.ts CHANGED
@@ -28,13 +28,13 @@ import type { ErrorTemplateInput, ExceptionFormatterClass, Ferors, Logger } from
28
28
  * throw errors.USER_NOT_FOUND.execute({ userId: '123' });
29
29
  */
30
30
  export declare class FockerorFactory<FormatterClass> {
31
- private readonly logger;
32
31
  private readonly formatterClass;
32
+ private readonly logger?;
33
33
  /**
34
34
  * @param logger - Экземпляр логгера (должен соответствовать интерфейсу Logger).
35
35
  * @param formatterClass - Класс для форматирования исключения (должен иметь конструктор, совместимый с Exception).
36
36
  */
37
- constructor(logger: Logger, formatterClass: ExceptionFormatterClass<FormatterClass>);
37
+ constructor(formatterClass: ExceptionFormatterClass<FormatterClass>, logger?: Logger | undefined);
38
38
  /**
39
39
  * Генерирует набор ошибок для указанного префикса и шаблонов.
40
40
  * Для каждого шаблона создаётся экземпляр `Fockeror` с автоматически вычисленными плейсхолдерами.
package/dist/factory.js CHANGED
@@ -32,15 +32,15 @@ const fockeror_1 = require("./fockeror");
32
32
  * throw errors.USER_NOT_FOUND.execute({ userId: '123' });
33
33
  */
34
34
  class FockerorFactory {
35
- logger;
36
35
  formatterClass;
36
+ logger;
37
37
  /**
38
38
  * @param logger - Экземпляр логгера (должен соответствовать интерфейсу Logger).
39
39
  * @param formatterClass - Класс для форматирования исключения (должен иметь конструктор, совместимый с Exception).
40
40
  */
41
- constructor(logger, formatterClass) {
42
- this.logger = logger;
41
+ constructor(formatterClass, logger) {
43
42
  this.formatterClass = formatterClass;
43
+ this.logger = logger;
44
44
  }
45
45
  /**
46
46
  * Генерирует набор ошибок для указанного префикса и шаблонов.
@@ -58,12 +58,12 @@ class FockerorFactory {
58
58
  const input = templates[key];
59
59
  const errorTemplate = this.defineError(input);
60
60
  const code = this.generateCode(prefix, key, index);
61
- this.logger.execute(`Загрузка ошибки ${prefix} ${code} : ${errorTemplate.message}`);
61
+ this.logger?.execute?.(`Загрузка ошибки ${prefix} ${code} : ${errorTemplate.message}`);
62
62
  const prefixed = {
63
63
  ...errorTemplate,
64
64
  message: `${code} : ${errorTemplate.message}`,
65
65
  };
66
- const fockeror = new fockeror_1.Fockeror(prefixed, this.logger, this.formatterClass);
66
+ const fockeror = new fockeror_1.Fockeror(prefixed, this.formatterClass, this.logger);
67
67
  return [key, fockeror];
68
68
  });
69
69
  return Object.fromEntries(entries);
@@ -76,7 +76,7 @@ class FockerorFactory {
76
76
  defineError(error) {
77
77
  const combined = `${error.message} ${error.description}`;
78
78
  const matches = combined.match(constants_1.PLACEHOLDER_PATTERN);
79
- const allKeys = matches?.map((m) => m.slice(1, -1)) ?? [];
79
+ const allKeys = matches?.map((m) => m.slice(constants_1.OFFSETS.START, constants_1.OFFSETS.END)) ?? [];
80
80
  const uniqueKeys = Array.from(new Set(allKeys));
81
81
  return { ...error, placeholders: uniqueKeys };
82
82
  }
@@ -19,8 +19,8 @@ import type { ErrorTemplate, ExceptionFormatterClass, Logger, PlaceholderObject
19
19
  */
20
20
  export declare class Fockeror<const Placeholders extends string[], FormatterClass> {
21
21
  readonly template: ErrorTemplate<Placeholders>;
22
- private readonly logger;
23
22
  private readonly formatterClass;
23
+ private readonly logger?;
24
24
  private readonly placeholderRegexes;
25
25
  /**
26
26
  * Создаёт экземпляр Fockeror.
@@ -29,7 +29,7 @@ export declare class Fockeror<const Placeholders extends string[], FormatterClas
29
29
  * @param formatterClass - Класс для форматирования исключения в специфичный для фреймворка тип.
30
30
  * @throws {Error} Если объявленные в `placeholders` ключи не соответствуют реально найденным в тексте.
31
31
  */
32
- constructor(template: ErrorTemplate<Placeholders>, logger: Logger, formatterClass: ExceptionFormatterClass<FormatterClass>);
32
+ constructor(template: ErrorTemplate<Placeholders>, formatterClass: ExceptionFormatterClass<FormatterClass>, logger?: Logger | undefined);
33
33
  execute(placeholders: PlaceholderObject<Placeholders>, cause?: Error): FormatterClass;
34
34
  execute(cause?: Error): FormatterClass;
35
35
  throw(placeholders: PlaceholderObject<Placeholders>, cause?: Error): never;
package/dist/fockeror.js CHANGED
@@ -23,8 +23,8 @@ const exception_1 = require("./exception");
23
23
  */
24
24
  class Fockeror {
25
25
  template;
26
- logger;
27
26
  formatterClass;
27
+ logger;
28
28
  placeholderRegexes;
29
29
  /**
30
30
  * Создаёт экземпляр Fockeror.
@@ -33,10 +33,10 @@ class Fockeror {
33
33
  * @param formatterClass - Класс для форматирования исключения в специфичный для фреймворка тип.
34
34
  * @throws {Error} Если объявленные в `placeholders` ключи не соответствуют реально найденным в тексте.
35
35
  */
36
- constructor(template, logger, formatterClass) {
36
+ constructor(template, formatterClass, logger) {
37
37
  this.template = template;
38
- this.logger = logger;
39
38
  this.formatterClass = formatterClass;
39
+ this.logger = logger;
40
40
  this.placeholderRegexes = this.extractPlaceholders(template);
41
41
  }
42
42
  /**
@@ -99,7 +99,7 @@ class Fockeror {
99
99
  for (const [key, regex] of this.placeholderRegexes.entries()) {
100
100
  const value = placeholders[key];
101
101
  if (value === undefined) {
102
- this.logger.error(new Error(`Placeholder \${{ ${key} }} not provided in data`));
102
+ this.logger?.error?.(new Error(`Placeholder \${{ ${key} }} not provided in data`));
103
103
  continue;
104
104
  }
105
105
  message = message.replace(regex, value);
@@ -146,7 +146,7 @@ class Fockeror {
146
146
  errors.push(new Error(`Placeholder from text "${placeholder}" not found in placeholders list`));
147
147
  }
148
148
  if (errors.length !== 0) {
149
- errors.forEach((e) => this.logger.error(e));
149
+ errors.forEach((e) => this.logger?.error?.(e));
150
150
  throw new Error("Placeholder validation failed.");
151
151
  }
152
152
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fockeror",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",