@reforgium/internal 1.0.2 → 1.1.1

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.
@@ -8,6 +8,14 @@ import { InjectionToken, signal, effect, untracked } from '@angular/core';
8
8
  * @type {InjectionToken<Signal<Langs>>}
9
9
  */
10
10
  const SELECTED_LANG = new InjectionToken('RE_SELECTED_LANG');
11
+ /**
12
+ * Injection token for language change provider.
13
+ * Provides access to method for changing the current application language.
14
+ * Can be overridden in app.config with a custom provider.
15
+ *
16
+ * @type {InjectionToken<ChangeLangProvider>}
17
+ */
18
+ const CHANGE_LANG = new InjectionToken('RE_CHANGE_LANG');
11
19
  /**
12
20
  * Injection token for translation provider.
13
21
  * Provides access to translation methods for message retrieval and namespace loading.
@@ -21,6 +29,7 @@ const TRANSLATION = new InjectionToken('RE_GET_LANG');
21
29
  * Can be overridden in app.config with a custom provider.
22
30
  */
23
31
  const SELECTED_THEME = new InjectionToken('RE_SELECTED_THEME');
32
+ const CHANGE_THEME = new InjectionToken('RE_CHANGE_THEME');
24
33
 
25
34
  /**
26
35
  * Injection token for the current device type as a Signal.
@@ -67,12 +76,12 @@ const VALIDATION_MESSAGES = new InjectionToken('RE_VALIDATION_MESSAGES', {
67
76
  });
68
77
 
69
78
  /**
70
- * Загружает файл из объекта Blob и предлагает пользователю сохранить его.
79
+ * Downloads a file from a Blob object and prompts the user to save it.
71
80
  *
72
- * @param {Blob} blob - Объект Blob, представляющий файл для загрузки.
73
- * @param {string} [fileName] - Опционально. Имя для загружаемого файла.
74
- * Если не указано, в качестве имени файла будет использоваться текущая метка времени.
75
- * @return {void} Не возвращает значение.
81
+ * @param {Blob} blob - Blob object representing the file to download.
82
+ * @param {string} [fileName] - Optional. Name for the downloaded file.
83
+ * If not specified, the current timestamp will be used as the filename.
84
+ * @return {void} Does not return a value.
76
85
  */
77
86
  function downloadByBlob(blob, fileName) {
78
87
  const win = window;
@@ -86,12 +95,12 @@ function downloadByBlob(blob, fileName) {
86
95
  }
87
96
  }
88
97
  /**
89
- * Инициирует загрузку файла по-указанному URL. Опционально можно указать пользовательское имя файла.
98
+ * Initiates a file download for the given URL. Optionally, a custom filename can be specified.
90
99
  *
91
- * @param {string} url - URL файла для загрузки.
92
- * @param {string} [filename] - Желаемое имя для загружаемого файла.
93
- * Если не указано, будет использовано имя на основе временной метки.
94
- * @return {void} Функция не возвращает значение.
100
+ * @param {string} url - URL of the file to download.
101
+ * @param {string} [filename] - Desired name for the downloaded file.
102
+ * If not specified, a timestamp-based name will be used.
103
+ * @return {void} The function does not return a value.
95
104
  */
96
105
  function downloadByUrl(url, filename) {
97
106
  const win = window;
@@ -105,12 +114,12 @@ function downloadByUrl(url, filename) {
105
114
  win.document.body.removeChild(a);
106
115
  }
107
116
  /**
108
- * Копирует указанный текст в буфер обмена. Использует Clipboard API, если доступен,
109
- * в противном случае использует `document.execCommand` в качестве запасного метода.
117
+ * Copies the specified text to the clipboard. Uses the Clipboard API if available,
118
+ * otherwise falls back to `document.execCommand`.
110
119
  *
111
- * @param {string} text - Текст, который необходимо скопировать в буфер обмена.
112
- * @return {Promise<boolean>} Промис, который резолвится в boolean, указывающий, было ли
113
- * копирование текста успешным.
120
+ * @param {string} text - The text to copy to the clipboard.
121
+ * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether
122
+ * the text copying was successful.
114
123
  */
115
124
  async function copyText(text) {
116
125
  const win = window;
@@ -136,13 +145,13 @@ async function copyText(text) {
136
145
  return ok;
137
146
  }
138
147
  /**
139
- * Преобразует строку в формате Base64 в объект Blob.
148
+ * Converts a Base64 encoded string to a Blob object.
140
149
  *
141
- * @param {string} base64 - Строка в формате Base64. Может опционально включать MIME-тип
142
- * в формате `data:<mimeType>;base64,<data>`.
143
- * @param {string} [mimeType=''] - MIME-тип данных. Необязательный параметр, будет переопределен,
144
- * если `base64` включает MIME-тип.
145
- * @return {Blob} Объект Blob, созданный из строки в формате Base64.
150
+ * @param {string} base64 - Base64 encoded string. Can optionally include a MIME type
151
+ * in the format `data:<mimeType>;base64,<data>`.
152
+ * @param {string} [mimeType=''] - MIME type of the data. Optional parameter, will be overridden
153
+ * if the `base64` string includes a MIME type.
154
+ * @return {Blob} A Blob object created from the Base64 string.
146
155
  */
147
156
  function base64ToBlob(base64, mimeType = '') {
148
157
  const matches = base64.match(/^data:(.+);base64,(.*)$/);
@@ -157,6 +166,27 @@ function base64ToBlob(base64, mimeType = '') {
157
166
  return new Blob([byteArray], { type: mime });
158
167
  }
159
168
 
169
+ /**
170
+ * Creates a debounced signal that delays updates from the source signal.
171
+ * The output signal will only update after the specified delay has passed without new values.
172
+ *
173
+ * @template T - The type of the signal value
174
+ * @param {Signal<T>} src - The source signal to debounce
175
+ * @param {number} [ms=150] - The debounce delay in milliseconds (default: 150ms)
176
+ * @param {Object} [opts] - Optional configuration
177
+ * @param {Injector} [opts.injector] - Optional injector for the effect context
178
+ * @returns {Signal<T>} A readonly signal that emits debounced values from the source
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * const searchQuery = signal('');
183
+ * const debouncedQuery = debounceSignal(searchQuery, 300);
184
+ *
185
+ * effect(() => {
186
+ * console.log('Debounced value:', debouncedQuery());
187
+ * });
188
+ * ```
189
+ */
160
190
  const debounceSignal = (src, ms = 150, opts) => {
161
191
  const out = signal(src(), ...(ngDevMode ? [{ debugName: "out" }] : []));
162
192
  let timeoutRef;
@@ -173,6 +203,29 @@ const debounceSignal = (src, ms = 150, opts) => {
173
203
  }, { injector: opts?.injector });
174
204
  return out.asReadonly();
175
205
  };
206
+ /**
207
+ * Creates a throttled signal that limits the rate of updates from the source signal.
208
+ * The output signal will emit the first value immediately, then wait for the specified delay
209
+ * before allowing subsequent updates. If values are emitted during the waiting period,
210
+ * the last value will be queued and emitted after the delay.
211
+ *
212
+ * @template T - The type of the signal value
213
+ * @param {Signal<T>} src - The source signal to throttle
214
+ * @param {number} [ms=100] - The throttle delay in milliseconds (default: 100ms)
215
+ * @param {Object} [opts] - Optional configuration
216
+ * @param {Injector} [opts.injector] - Optional injector for the effect context
217
+ * @returns {Signal<T>} A readonly signal that emits throttled values from the source
218
+ *
219
+ * @example
220
+ * ```typescript
221
+ * const scrollPosition = signal(0);
222
+ * const throttledPosition = throttleSignal(scrollPosition, 200);
223
+ *
224
+ * effect(() => {
225
+ * console.log('Throttled position:', throttledPosition());
226
+ * });
227
+ * ```
228
+ */
176
229
  const throttleSignal = (src, ms = 100, opts) => {
177
230
  const out = signal(src(), ...(ngDevMode ? [{ debugName: "out" }] : []));
178
231
  let last = 0;
@@ -218,19 +271,19 @@ const throttleSignal = (src, ms = 100, opts) => {
218
271
 
219
272
  const pad = (n) => n.toString().padStart(2, '0');
220
273
  /**
221
- * Форматирует объект даты в строку заданного формата.
274
+ * Formats a Date object into a string of the given format.
222
275
  *
223
- * @param {Date} date - Объект даты для форматирования.
224
- * @param {string} [format='yyyy-MM-dd'] - Строковый формат для применения. По умолчанию 'yyyy-MM-dd'.
225
- * Поддерживаемые токены в строке формата:
226
- * - yyyy: Полный год (например, 2023)
227
- * - MM: Месяц с ведущим нулем (01-12)
228
- * - dd: День месяца с ведущим нулем (01-31)
229
- * - HH: Час в 24-часовом формате с ведущим нулем (00-23)
230
- * - mm: Минуты с ведущим нулем (00-59)
231
- * - ss: Секунды с ведущим нулем (00-59)
276
+ * @param {Date} date - Date object to format.
277
+ * @param {string} [format='yyyy-MM-dd'] - String format to apply. Defaults to 'yyyy-MM-dd'.
278
+ * Supported tokens in the format string:
279
+ * - yyyy: Full year (e.g., 2023)
280
+ * - MM: Month with leading zero (01-12)
281
+ * - dd: Day of the month with leading zero (01-31)
282
+ * - HH: Hour in 24-hour format with leading zero (00-23)
283
+ * - mm: Minutes with leading zero (00-59)
284
+ * - ss: Seconds with leading zero (00-59)
232
285
  *
233
- * @returns {string} Отформатированная строка даты. Возвращает пустую строку, если входная дата некорректна.
286
+ * @returns {string} Formatted date string. Returns an empty string if the input date is invalid.
234
287
  */
235
288
  const formatDate = (date, format = 'yyyy-MM-dd') => {
236
289
  if (isNaN(date['getTime']?.())) {
@@ -251,11 +304,11 @@ const formatDate = (date, format = 'yyyy-MM-dd') => {
251
304
  return formatted;
252
305
  };
253
306
  /**
254
- * Форматирует заданную дату в локализованную строковую репрезентацию в формате 'день месяц год'.
255
- * Месяц локализован для 'ru-RU' локали и сокращен.
307
+ * Formats the given date into a localized string representation in the format 'day month year'.
308
+ * The month is localized for 'ru-RU' locale and abbreviated.
256
309
  *
257
- * @param {Date} date - Объект даты для форматирования.
258
- * @return {string} Строка, представляющая отформатированную дату в формате 'день месяц год'.
310
+ * @param {Date} date - Date object to format.
311
+ * @return {string} A string representing the formatted date in the format 'day month year'.
259
312
  */
260
313
  function formatToLocaledDate(date) {
261
314
  const day = date.getDate();
@@ -264,12 +317,12 @@ function formatToLocaledDate(date) {
264
317
  return `${day} ${month} ${year}`;
265
318
  }
266
319
  /**
267
- * Парсит дату из строки по заданной маске.
268
- * Поддерживает dd, MM, yyyy, HH, mm, ss.
269
- * Разделители любые: '.', '/', '-',' '.
320
+ * Parses a date from a string based on the given mask.
321
+ * Supports dd, MM, yyyy, HH, mm, ss.
322
+ * Any delimiters: '.', '/', '-', ' '.
270
323
  *
271
- * @param {string} value - исходная строка с датой
272
- * @param {string} format - маска, например "dd.MM.yyyy"
324
+ * @param {string} value - source date string
325
+ * @param {string} format - mask, e.g., "dd.MM.yyyy"
273
326
  * @returns {Date|null}
274
327
  */
275
328
  const parseToDate = (value, format = 'dd.MM.yyyy') => {
@@ -298,19 +351,19 @@ const parseToDate = (value, format = 'dd.MM.yyyy') => {
298
351
  return date;
299
352
  };
300
353
  /**
301
- * Парсит строковое представление двух дат в кортеж объектов `Date` или значений `null`.
354
+ * Parses a string representation of two dates into a tuple of `Date` objects or `null` values.
302
355
  *
303
- * Эта функция пытается извлечь и разобрать два значения даты из входной строки
304
- * на основе предоставленного формата даты. Если парсинг неуспешен, возвращаемый кортеж будет
305
- * состоять из значений `null`. По умолчанию ожидаемый формат даты - `dd.MM.yyyy`, но он
306
- * может быть изменен.
356
+ * This function attempts to extract and parse two date values from the input string
357
+ * based on the provided date format. If parsing is unsuccessful, the returned tuple will
358
+ * consist of `null` values. The default expected date format is `dd.MM.yyyy`, but it
359
+ * can be changed.
307
360
  *
308
- * @param {string | null} value - Строка, содержащая представления дат для разбора.
309
- * Если `null`, функция вернет `[null, null]`.
310
- * @param {string} [format='dd.MM.yyyy'] - Формат даты, используемый для парсинга.
311
- * Поддерживает `yyyy`, `MM`, `dd`, `HH`, `mm` и `ss`.
312
- * @returns {[Date | null, Date | null]} Кортеж, где первый элемент - разобранная начальная дата
313
- * и второй элемент - разобранная конечная дата. Если парсинг не удался, оба элемента будут `null`.
361
+ * @param {string | null} value - String containing date representations to parse.
362
+ * If `null`, the function will return `[null, null]`.
363
+ * @param {string} [format='dd.MM.yyyy'] - Date format used for parsing.
364
+ * Supports `yyyy`, `MM`, `dd`, `HH`, `mm`, and `ss`.
365
+ * @returns {[Date | null, Date | null]} A tuple where the first element is the parsed start date
366
+ * and the second element is the parsed end date. If parsing fails, both elements will be `null`.
314
367
  */
315
368
  const parseToDatePeriod = (value, format = 'dd.MM.yyyy') => {
316
369
  if (typeof value !== 'string' || !format) {
@@ -335,21 +388,21 @@ const parseToDatePeriod = (value, format = 'dd.MM.yyyy') => {
335
388
  }
336
389
  };
337
390
  /**
338
- * Определяет, является ли переданное значение периодом дат.
391
+ * Determines if the given value is a date period.
339
392
  *
340
- * Период дат представляется в виде массива, содержащего ровно два экземпляра Date.
341
- * Оба элемента массива должны быть корректными объектами Date (т.е. не `Invalid Date`).
393
+ * A date period is represented as an array containing exactly two Date instances.
394
+ * Both elements of the array must be valid Date objects (i.e., not `Invalid Date`).
342
395
  *
343
- * @param {unknown} value - Значение для проверки.
344
- * @returns {value is [Date, Date]} - Возвращает `true`, если значение является корректным периодом дат, иначе `false`.
396
+ * @param {unknown} value - Value to check.
397
+ * @returns {value is [Date, Date]} - Returns `true` if the value is a valid date period, otherwise `false`.
345
398
  */
346
399
  const isDatePeriod = (value) => Array.isArray(value) && value.length === 2 && value.every((it) => it instanceof Date && !isNaN(it.getTime()));
347
400
  /**
348
- * Преобразует различные типы данных в объект Date.
401
+ * Converts various data types to a Date object.
349
402
  *
350
- * @param {unknown} v - Значение для преобразования. Может быть объектом Date,
351
- * числом (timestamp) или строкой, содержащей корректную дату.
352
- * @returns {Date} Объект Date. Если преобразование невозможно, возвращает Invalid Date.
403
+ * @param {unknown} v - Value to convert. Can be a Date object,
404
+ * a number (timestamp), or a string containing a valid date.
405
+ * @returns {Date} Date object. If conversion is impossible, returns Invalid Date.
353
406
  */
354
407
  const toDate = (v) => {
355
408
  if (v instanceof Date)
@@ -361,8 +414,8 @@ const toDate = (v) => {
361
414
  return new Date(NaN);
362
415
  };
363
416
  /**
364
- * Переводит строку даты из заданного формата в ISO (UTC).
365
- * Пример:
417
+ * Converts a date string from a given format to ISO (UTC).
418
+ * Example:
366
419
  * reformatDateToISO("24.11.2025", "dd.MM.yyyy")
367
420
  * → "2025-11-24T00:00:00.000Z"
368
421
  */
@@ -412,27 +465,27 @@ function reformatDateToISO(dateStr, mask) {
412
465
  }
413
466
 
414
467
  /**
415
- * Определяет, является ли переданное значение null или undefined, опционально учитывая
416
- * пустые строки как null-подобные значения.
468
+ * Determines if the given value is null or undefined, optionally considering
469
+ * empty strings as null-like values.
417
470
  *
418
- * @param {unknown} value - Значение для проверки на null или undefined.
419
- * @param {boolean} [withEmptyString=false] - Если true, пустые строки также считаются
420
- * null-подобными значениями в дополнение к null и undefined.
421
- * @returns {value is null | undefined} Возвращает `true`, если значение равно null, undefined,
422
- * или (если `withEmptyString` равно true) пустой строке. В противном случае возвращает `false`.
471
+ * @param {unknown} value - Value to check for null or undefined.
472
+ * @param {boolean} [withEmptyString=false] - If true, empty strings are also considered
473
+ * null-like values in addition to null and undefined.
474
+ * @returns {value is null | undefined} Returns `true` if the value is null, undefined,
475
+ * or (if `withEmptyString` is true) an empty string. Otherwise returns `false`.
423
476
  */
424
477
  const isNullable = (value, withEmptyString = false) => value === null || value === undefined || (withEmptyString ? value === '' : false);
425
478
  /**
426
- * Проверяет, является ли переданное значение числом или может быть преобразовано в корректное число.
479
+ * Checks if the given value is a number or can be converted to a valid number.
427
480
  *
428
- * Эта функция проверяет, является ли входное значение числовым. Если входное значение
429
- * имеет тип number, проверяется, что оно является конечным числом и не NaN. Если входное
430
- * значение является строкой, проверяется возможность преобразования этой строки в корректное число.
481
+ * This function checks if the input value is numeric. If the input value
482
+ * is of type number, it is verified to be a finite number and not NaN. If the input
483
+ * value is a string, it checks if this string can be converted to a valid number.
431
484
  *
432
- * @param {unknown} value - Значение для проверки.
433
- * @param {boolean} [fromString=false] - Если true, строковые значения будут пытаться преобразоваться в число.
434
- * @returns {value is number} `true` если значение является числом или строкой,
435
- * которую можно преобразовать в число; иначе `false`.
485
+ * @param {unknown} value - Value to check.
486
+ * @param {boolean} [fromString=false] - If true, string values will attempt to be converted to a number.
487
+ * @returns {value is number} `true` if the value is a number or a string
488
+ * that can be converted to a number; otherwise `false`.
436
489
  */
437
490
  const isNumber = (value, fromString = false) => {
438
491
  if (typeof value === 'number') {
@@ -522,12 +575,12 @@ const concatArray = (value, mode, key) => {
522
575
  };
523
576
 
524
577
  /**
525
- * Форматирует число или строку, содержащую число, добавляя пробелы в качестве разделителей тысяч.
578
+ * Formats a number or a string containing a number by adding spaces as thousands separators.
526
579
  *
527
- * @param {number|string} num - Число или строка для форматирования.
528
- * Если входное значение null, undefined или недопустимое число, возвращается пустая строка.
529
- * @return {string} Отформатированная строка с пробелами в качестве разделителей тысяч или пустая строка,
530
- * если входные данные недопустимы.
580
+ * @param {number|string} num - The number or string to format.
581
+ * If the input value is null, undefined, or an invalid number, an empty string is returned.
582
+ * @return {string} Formatted string with spaces as thousands separators, or an empty string
583
+ * if the input is invalid.
531
584
  */
532
585
  function formatToSpacedNumber(num) {
533
586
  const stringed = String(num).replaceAll(' ', '');
@@ -538,13 +591,13 @@ function formatToSpacedNumber(num) {
538
591
  return str.replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
539
592
  }
540
593
  /**
541
- * Обрезает строку до указанного количества символов и добавляет многоточие ('…'),
542
- * если строка превышает лимит.
594
+ * Truncates a string to the specified number of characters and adds an ellipsis ('…')
595
+ * if the string exceeds the limit.
543
596
  *
544
- * @param {string} text - Текст для обрезки.
545
- * @param {number} limit - Максимально допустимая длина строки.
546
- * @returns {string} Обрезанная строка с многоточием, если длина превышает лимит,
547
- * или исходная строка, если нет.
597
+ * @param {string} text - The text to truncate.
598
+ * @param {number} limit - Maximum allowed string length.
599
+ * @returns {string} Truncated string with an ellipsis if length exceeds the limit,
600
+ * or the original string otherwise.
548
601
  */
549
602
  const truncate = (text, limit) => {
550
603
  return text.length > limit ? text.slice(0, limit) + '…' : text;
@@ -605,12 +658,12 @@ const getDirMap = (directions) => {
605
658
  };
606
659
 
607
660
  /**
608
- * Вычисляет доступное вертикальное пространство под заданным элементом в области просмотра.
661
+ * Calculates the available vertical space below the given element in the viewport.
609
662
  *
610
- * @param {Element} el - DOM элемент, для которого необходимо вычислить доступную высоту снизу.
611
- * @param {number} [margin=20] - Опциональное поле, вычитаемое из вычисленной доступной высоты.
612
- * @return {number} Доступная высота в пикселях под элементом с учетом поля.
613
- * Возвращает 0, если нет доступного пространства.
663
+ * @param {Element} el - DOM element for which to calculate the available height below.
664
+ * @param {number} [margin=20] - Optional margin subtracted from the calculated available height.
665
+ * @return {number} Available height in pixels below the element, taking margin into account.
666
+ * Returns 0 if there is no available space.
614
667
  */
615
668
  function getAvailableHeight(el, margin = 20) {
616
669
  const rect = el.getBoundingClientRect();
@@ -621,12 +674,12 @@ function getAvailableHeight(el, margin = 20) {
621
674
  }
622
675
 
623
676
  /**
624
- * Извлекает значение по вложенному пути внутри объекта или массива.
625
- * Путь указывается в виде строки с разделителями-точками.
677
+ * Retrieves a value by a nested path within an object or array.
678
+ * The path is specified as a dot-delimited string.
626
679
  *
627
- * @param obj Объект или массив для обхода.
628
- * @param path Строка с разделителями-точками, указывающая путь для извлечения значения.
629
- * @return Значение, найденное по указанному пути, или undefined, если путь не существует или недействителен.
680
+ * @param obj The object or array to traverse.
681
+ * @param path A dot-delimited string specifying the path to retrieve the value.
682
+ * @return The value found at the specified path, or undefined if the path does not exist or is invalid.
630
683
  */
631
684
  function getChainedValue(obj, path) {
632
685
  if (!obj) {
@@ -648,11 +701,11 @@ function getChainedValue(obj, path) {
648
701
  }
649
702
 
650
703
  /**
651
- * Нормализует заданный URL, удаляя избыточные слеши, разрешая сегменты с точками
652
- * и обеспечивая отсутствие завершающих слешей в конце URL.
704
+ * Normalizes a given URL by removing redundant slashes, resolving dot segments,
705
+ * and ensuring there are no trailing slashes at the end of the URL.
653
706
  *
654
- * @param {string} url - Строка URL для нормализации.
655
- * @return {string} - Нормализованная строка URL.
707
+ * @param {string} url - The URL string to normalize.
708
+ * @return {string} - The normalized URL string.
656
709
  */
657
710
  function normalizeUrl(url) {
658
711
  const [protocol, rest] = url.split('://');
@@ -663,14 +716,14 @@ function normalizeUrl(url) {
663
716
  return rest ? `${protocol}://${cleaned}` : cleaned;
664
717
  }
665
718
  /**
666
- * Заменяет заполнители в предоставленном URL-шаблоне соответствующими значениями из объекта params.
667
- * Заполнители определяются как `:key` в строке шаблона.
719
+ * Replaces placeholders in the provided URL template with corresponding values from the params object.
720
+ * Placeholders are defined as `:key` in the template string.
668
721
  *
669
- * @param {string} template URL-шаблон, содержащий заполнители для замены.
670
- * @param {AnyDict} [params] Опциональный словарь, содержащий пары ключ-значение.
671
- * Ключи соответствуют заполнителям в шаблоне, а значения заменят их.
672
- * @return {string} URL с заполнителями, замененными соответствующими значениями из объекта params.
673
- * По умолчанию возвращает исходный шаблон, если params не предоставлен.
722
+ * @param {string} template URL template containing placeholders to replace.
723
+ * @param {AnyDict} [params] Optional dictionary containing key-value pairs.
724
+ * Keys correspond to placeholders in the template, and values will replace them.
725
+ * @return {string} URL with placeholders replaced by corresponding values from the params object.
726
+ * Defaults to the original template if params is not provided.
674
727
  */
675
728
  function fillUrlWithParams(template, params) {
676
729
  if (!params) {
@@ -679,12 +732,12 @@ function fillUrlWithParams(template, params) {
679
732
  return template.replace(/:([a-zA-Z0-9_]+)/g, (_, k) => encodeURIComponent(params[k] ?? ''));
680
733
  }
681
734
  /**
682
- * Добавляет параметры запроса к указанному URL.
735
+ * Appends query parameters to the specified URL.
683
736
  *
684
- * @param {string} url Базовый URL, к которому будут добавлены параметры запроса.
685
- * @param {Record<string, unknown>} [params] Опциональный объект, содержащий пары ключ-значение параметров запроса.
686
- * Ключи со значениями null или undefined будут проигнорированы.
687
- * @return {string} URL с добавленными параметрами запроса.
737
+ * @param {string} url Base URL to which query parameters will be added.
738
+ * @param {Record<string, unknown>} [params] Optional object containing query parameter key-value pairs.
739
+ * Keys with null or undefined values will be ignored.
740
+ * @return {string} URL with appended query parameters.
688
741
  */
689
742
  function appendQueryParams(url, params) {
690
743
  if (!params || !Object.keys(params).length)
@@ -699,11 +752,11 @@ function appendQueryParams(url, params) {
699
752
  return `${base}?${searchParams.toString()}`;
700
753
  }
701
754
  /**
702
- * Разбирает строку запроса в объект, содержащий пары ключ-значение.
755
+ * Parses a query string into an object containing key-value pairs.
703
756
  *
704
- * @param {string} query - Строка запроса для разбора. Может начинаться с '?'.
705
- * @return {Record<string, string>} Объект, где каждый ключ - это имя параметра запроса,
706
- * а значение - соответствующее значение.
757
+ * @param {string} query - The query string to parse. May start with '?'.
758
+ * @return {Record<string, string>} An object where each key is a query parameter name,
759
+ * and the value is the corresponding value.
707
760
  */
708
761
  function parseQueryParams(query) {
709
762
  const search = query.startsWith('?') ? query.slice(1) : query;
@@ -718,13 +771,13 @@ function parseQueryParams(query) {
718
771
  /**
719
772
  * Constructs a query string from a given object and concatenation type.
720
773
  *
721
- * @param {Record<string, any>} object - Объект с парами ключ-значение для преобразования в строку запроса.
722
- * Ключи представляют имена параметров, а значения - значения параметров.
723
- * @param {'comma' | 'json' | 'multi'} concatType - Метод обработки значений массива:
724
- * - 'comma': Объединяет элементы массива через запятую.
725
- * - 'json': Сериализует массив как JSON строку.
726
- * - 'multi': Создает несколько записей для элементов массива, где каждый связан с одним и тем же ключом.
727
- * @returns {string} - Сформированная строка запроса с закодированными как URI компоненты ключами и значениями.
774
+ * @param {Record<string, any>} object - Object with key-value pairs to convert into a query string.
775
+ * Keys represent parameter names, and values represent parameter values.
776
+ * @param {'comma' | 'json' | 'multi'} concatType - Method for handling array values:
777
+ * - 'comma': Joins array elements with a comma.
778
+ * - 'json': Serializes the array as a JSON string.
779
+ * - 'multi': Creates multiple entries for array elements, each associated with the same key.
780
+ * @returns {string} - Formed query string with keys and values encoded as URI components.
728
781
  */
729
782
  const makeQuery = (object, concatType) => {
730
783
  return Object.entries(object)
@@ -739,16 +792,16 @@ const makeQuery = (object, concatType) => {
739
792
  .join('&');
740
793
  };
741
794
  /**
742
- * Сравнивает два маршрута, чтобы определить, совпадает ли фактический маршрут с шаблоном маршрута.
743
- * Поддерживает статическое и динамическое сопоставление маршрутов с опциональным учетом подмаршрутов.
795
+ * Compares two routes to determine if the actual route matches the route template.
796
+ * Supports static and dynamic route matching with optional subroute consideration.
744
797
  *
745
- * @param {string} actualRoute - Фактический путь маршрута для сравнения.
746
- * @param {string} pureRoute - Шаблонный путь маршрута для сопоставления, который может включать заполнители
747
- * (например, `:id`).
748
- * @param {boolean} [withSubroute=false] - Определяет, разрешать ли сопоставление подмаршрутов. Если true,
749
- * actualRoute должен начинаться с заполненного pureRoute.
750
- * @return {boolean} Возвращает true, если фактический маршрут соответствует шаблонному
751
- * маршруту (и опциональному условию подмаршрута, если включено), в противном случае false.
798
+ * @param {string} actualRoute - Actual route path to compare.
799
+ * @param {string} pureRoute - Template route path to match, which may include placeholders
800
+ * (e.g., `:id`).
801
+ * @param {boolean} [withSubroute=false] - Determines whether to allow subroute matching. If true,
802
+ * actualRoute must start with the filled pureRoute.
803
+ * @return {boolean} Returns true if the actual route matches the template
804
+ * route (and optional subroute condition if enabled), otherwise false.
752
805
  */
753
806
  const compareRoutes = (actualRoute, pureRoute, withSubroute = false) => {
754
807
  if (!pureRoute.includes(':')) {
@@ -760,12 +813,12 @@ const compareRoutes = (actualRoute, pureRoute, withSubroute = false) => {
760
813
  }
761
814
  };
762
815
  /**
763
- * Обрабатывает и материализует путь маршрута путем декодирования и при необходимости замены параметров маршрута.
816
+ * Processes and materializes a route path by decoding and, if necessary, replacing route parameters.
764
817
  *
765
- * @param {string} actualRoute - Фактический путь маршрута, обычно предоставляемый
766
- * в качестве источника значений динамических параметров.
767
- * @param {string} pureRoute - Шаблон пути маршрута, может включать динамические сегменты, обозначенные `:`.
768
- * @returns {string} Полностью материализованный и декодированный путь маршрута.
818
+ * @param {string} actualRoute - Actual route path, usually provided
819
+ * as a source for dynamic parameter values.
820
+ * @param {string} pureRoute - Route path template, may include dynamic segments denoted by `:`.
821
+ * @returns {string} Fully materialized and decoded route path.
769
822
  */
770
823
  const materializeRoutePath = (actualRoute, pureRoute) => {
771
824
  if (!pureRoute.includes(':')) {
@@ -789,14 +842,14 @@ const fillRouteTemplate = (actualRoute, pureRoute) => {
789
842
  };
790
843
 
791
844
  /**
792
- * Рекурсивно проверяет равенство двух объектов, включая вложенные структуры и особые случаи,
793
- * такие как массивы, наборы, карты, даты и NaN.
845
+ * Recursively checks the equality of two objects, including nested structures and special cases
846
+ * such as arrays, sets, maps, dates, and NaN.
794
847
  *
795
- * @param {AnyType} a - Первый объект для сравнения.
796
- * @param {AnyType} b - Второй объект для сравнения.
797
- * @param {Map} [seen=new Map()] - Карта, используемая для обнаружения циклических ссылок
798
- * при глубокой проверке равенства.
799
- * @return {boolean} - Возвращает true, если объекты полностью равны, иначе возвращает false.
848
+ * @param {AnyType} a - The first object to compare.
849
+ * @param {AnyType} b - The second object to compare.
850
+ * @param {Map} [seen=new Map()] - A map used to detect cyclic references
851
+ * during deep equality check.
852
+ * @return {boolean} - Returns true if the objects are deeply equal, otherwise returns false.
800
853
  */
801
854
  function deepEqual(a, b, seen = new Map()) {
802
855
  if (a === b) {
@@ -849,5 +902,5 @@ const generateId = (limit = 15, radix = 36) => Math.random()
849
902
  * Generated bundle index. Do not edit.
850
903
  */
851
904
 
852
- export { CURRENT_DEVICE, SELECTED_LANG, SELECTED_THEME, TRANSLATION, VALIDATION_MESSAGES, appendQueryParams, base64ToBlob, compareRoutes, concatArray, copyText, debounceSignal, deepEqual, downloadByBlob, downloadByUrl, fillUrlWithParams, formatDate, formatToLocaledDate, formatToSpacedNumber, generateId, getAvailableHeight, getChainedValue, getCorrectedPosition, isDatePeriod, isNullable, isNumber, isObject, makeQuery, materializeRoutePath, normalizeUrl, parseQueryArray, parseQueryParams, parseToDate, parseToDatePeriod, reformatDateToISO, throttleSignal, toDate, truncate };
905
+ export { CHANGE_LANG, CHANGE_THEME, CURRENT_DEVICE, SELECTED_LANG, SELECTED_THEME, TRANSLATION, VALIDATION_MESSAGES, appendQueryParams, base64ToBlob, compareRoutes, concatArray, copyText, debounceSignal, deepEqual, downloadByBlob, downloadByUrl, fillUrlWithParams, formatDate, formatToLocaledDate, formatToSpacedNumber, generateId, getAvailableHeight, getChainedValue, getCorrectedPosition, isDatePeriod, isNullable, isNumber, isObject, makeQuery, materializeRoutePath, normalizeUrl, parseQueryArray, parseQueryParams, parseToDate, parseToDatePeriod, reformatDateToISO, throttleSignal, toDate, truncate };
853
906
  //# sourceMappingURL=reforgium-internal.mjs.map