@dxtmisha/functional-basic 1.11.2 → 2.0.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/CHANGELOG.md CHANGED
@@ -2,6 +2,407 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [2.0.0] - 2026-11-03
6
+
7
+ ### Added
8
+ - **`forOwn`**:
9
+ - Safe object traversal utility skipping prototype pollution keys (`'__proto__'`, `'constructor'`, `'prototype'`) and non-enumerable properties with optional early break return.
10
+ - Exported in public library exports (`src/library.ts`).
11
+ - Added comprehensive unit test suite in `src/functions/__tests__/forOwn.test.ts`.
12
+ - Added trilingual Storybook documentation (EN, RU, VI).
13
+ - **`toGeoItem` / `toGeoItemFull` / `toGeoStandard` / `toLocale`**:
14
+ - `toGeoItem`: resolves standardized `GeoItem` records from country and language inputs with localized fallbacks.
15
+ - `toGeoItemFull`: creates comprehensive `GeoItemFull` metadata containing location, language, and country codes.
16
+ - `toGeoStandard`: transforms raw country and language maps into structured `GeoItem` records.
17
+ - `toLocale`: creates and formats standard BCP-47 locale tags (`en-US`, `vi-VN`) from country and language codes.
18
+ - Exported in public library exports (`src/library.ts`).
19
+ - Added comprehensive unit test suites and trilingual Storybook documentation (EN, RU, VI).
20
+ - **`setElementItemStyle` / `setElementItemAttribute` / `setElementItemProperty`**:
21
+ - Modular DOM mutation utilities extracted from `setElementItem`.
22
+ - `setElementItemStyle`: manages CSS style declarations, CSS custom properties (`--*`), kebab-case property normalization, `!important` suffix extraction, and nullish property removal.
23
+ - `setElementItemAttribute`: manages HTML and ARIA attributes with boolean ARIA serialization (`'true'` / `'false'`), boolean flag toggling, and numeric / BigInt coercion.
24
+ - `setElementItemProperty`: safely sets element properties and performs deep merges with prototype pollution protection.
25
+ - Exported in public library exports (`src/library.ts`).
26
+ - Added unit test suites and trilingual Storybook documentation for each utility.
27
+ - **`GeoLocation` / `GeoList` / `GeoTimezone`**:
28
+ - Modular decomposition of the monolithic `GeoInstance` class for location resolution, global country database querying, and time zone offset management.
29
+ - `GeoLocation`: tiered resolution (Cookie -> Storage -> DOM), BCP-47 normalization, and dynamic location synchronization.
30
+ - `GeoList`: immutable query methods and mutation APIs for country, phone, language, and continent datasets.
31
+ - `GeoTimezone`: time zone offset parsing, ISO 8601 formatting, and zone normalization.
32
+ - Exported in public library exports (`src/library.ts`).
33
+ - Added comprehensive test suites and trilingual Storybook documentation.
34
+ - **`toCountry` / `toLanguage` / `sanitizeLocation`**:
35
+ - `toCountry`: extracts normalized 2-letter ISO 3166-1 alpha-2 country codes from locale tags or country names, with `isRaw` fallback option.
36
+ - `toLanguage`: extracts normalized 2-letter ISO 639-1 language codes from locale strings, with `isRaw` fallback option.
37
+ - `sanitizeLocation`: validates and canonicalizes BCP-47 locale tags using length bounds, regex validation, and `Intl.Locale`.
38
+ - Exported in public library exports (`src/library.ts`).
39
+ - Added unit tests and trilingual Storybook documentation.
40
+ - **`removeTag`**:
41
+ - Utility for stripping HTML/XML tags, comments, DOCTYPE declarations, and CDATA blocks with customizable tag whitelisting/filtering and regex caching.
42
+ - Exported in public library exports (`src/library.ts`).
43
+ - Added unit tests and trilingual Storybook documentation.
44
+ - **`getObjectNull`**:
45
+ - Helper to create clean prototype-less objects (`Object.create(null)`) for safe key-value dictionary storage.
46
+ - Exported in public library exports (`src/library.ts`).
47
+ - Added unit tests and trilingual Storybook documentation.
48
+ - **`hasKeys`**:
49
+ - Zero-allocation property inspection utility checking for the presence of multiple keys on an object.
50
+ - Exported in public library exports (`src/library.ts`).
51
+ - Added unit tests and trilingual Storybook documentation.
52
+ - **`isRegExp`**:
53
+ - Cross-realm `RegExp` type predicate utility.
54
+ - Exported in public library exports (`src/library.ts`).
55
+ - Added unit tests and trilingual Storybook documentation.
56
+ - **`domElementsFromPoint`**:
57
+ - SSR-safe wrapper around `document.elementsFromPoint`.
58
+ - Exported in public library exports (`src/library.ts`).
59
+ - Added comprehensive test suite and trilingual Storybook documentation (EN, RU, VI).
60
+
61
+ ### Changed
62
+ - **`Datetime`**:
63
+ - Refactored `standard()` to construct formatted date-time strings directly from date parts, returning an empty string for invalid dates.
64
+ - Added `getCode(): string` accessor to retrieve current locale code.
65
+ - Added `getWeekday(): number` method to get day of the week (0 = Sunday).
66
+ - Optimized `getMaxDay()` calculation without allocating intermediate cloned date instances.
67
+ - Clamped days of the month in `setYear()` and `setMonth()` to prevent unintentional month overflow on shorter months.
68
+ - Introduced `block` flag preventing duplicate watch callbacks during composite operations.
69
+ - Integrated `ErrorCenter.on` error logging for invalid dates in `setDate()`.
70
+ - Supported optional parameters in `setDate()`, `setCode()`, and `setWatch()`.
71
+ - Expanded unit test suite and updated trilingual Storybook documentation.
72
+ - **`Geo` / `GeoInstance`**:
73
+ - `Geo`: added protected constructor to enforce static utility usage; aligned static facade methods (`get`, `getItem`, `getFirstItem`, `getFlag`, `getFlagList`).
74
+ - `GeoInstance`: decomposed extraction logic to modular utilities (`toGeoItem`, `toGeoItemFull`, `toGeoStandard`, `toLocale`).
75
+ - `GeoInstance`: aligned getters with `GeoItemFull` metadata (`getLanguage()` returns `item.language`, `getLocationCountry()` and `getLocationLanguage()` return `item.locationCountry` and `item.locationLanguage`).
76
+ - `GeoLocation`: delegated country and language extraction to `toCountry` and `toLanguage` with raw fallback support.
77
+ - **`getFirst`**:
78
+ - Unified implementation and signature symmetry with `getLast` (`readonly T[] | null | undefined`, duck-typed collections).
79
+ - Optimized object key retrieval via `Object.keys()` without array allocations.
80
+ - Expanded unit test coverage and updated trilingual Storybook documentation.
81
+ - **`getImageSrc` / `getElementImage` / `resizeImageByMax`**:
82
+ - `getImageSrc`: widened parameter types to accept `HTMLImageElement | string | Record<string, unknown> | null | undefined`, preventing runtime `TypeError` on non-string primitives using `isObject`.
83
+ - `getElementImage`: widened source parameter typing to `string | HTMLImageElement | Record<string, unknown> | null | undefined` with duck-typed `HTMLImageElement` checking.
84
+ - `resizeImageByMax`: refined typing and fallback handling when image is within constraints.
85
+ - Expanded unit tests and synchronized trilingual Storybook documentation.
86
+ - **`encodeLiteAttribute` / `copyObjectLite`**:
87
+ - `encodeLiteAttribute`: widened parameter typing to `text?: string | number | null` and added fast-path bypass for strings without special characters via `REGEXP_HAS_SPECIAL_CHARACTERS_LITE`.
88
+ - `copyObjectLite`: widened parameter typing to optional `source?: unknown` and added prototype isolation tests.
89
+ - Synchronized trilingual Storybook documentation.
90
+ - **`domQuerySelector` / `domQuerySelectorAll`**:
91
+ - Added `@template E extends Element = HTMLElement` JSDoc annotations for typed element query narrowing.
92
+ - **`createElement` / `domContentLoaded`**:
93
+ - Refined SSR guards, promise resolution, and parameter options.
94
+ - Synchronized trilingual Storybook documentation and expanded unit tests.
95
+ - **`splice`**:
96
+ - Hardened with `forOwn` traversal protecting against prototype pollution on both target and replacement objects.
97
+ - Optimized local accumulation with `disableCopy = true`, reducing merging complexity from $O(N^2)$ to $O(N)$.
98
+ - Added defensive non-object target guard `!isObject(array)` returning `{}` (or a deep clone of `replacement`).
99
+ - Widened parameter types: `array?: ObjectItem<I> | null`, `replacement?: ObjectItem<I> | I | null`, `indexStart?: string | null` with generic item inference `<I = unknown>`.
100
+ - Added bilingual JSDoc `@warning` regarding plain JSON-like object scope.
101
+ - Authoritative 16-test suite added and trilingual Storybook documentation updated.
102
+ - **`replaceRecursive`**:
103
+ - Added `disableCopy: boolean = false` parameter (passed as `true` in self-recursion) to eliminate redundant nested deep clones and achieve linear $O(N)$ merge performance.
104
+ - Switched traversal to `forOwn`, automatically protecting against prototype pollution.
105
+ - Refined types to `<I = unknown>` and accepted `readonly I[] | null`.
106
+ - Added bilingual JSDoc `@warning` regarding plain JSON-like object scope.
107
+ - Expanded unit test suite to 19 tests and synchronized trilingual Storybook documentation.
108
+ - **`uniqueArray`**:
109
+ - Optimized deduplication with $O(N)$ `Set` fast-path for primitive arrays while preserving deep structural deduplication for objects.
110
+ - Accepted `readonly I[] | null` collections and hardened boundary checks.
111
+ - Expanded unit test suite and synchronized trilingual Storybook documentation.
112
+ - **`copyObject` / `copyObjectLite`**:
113
+ - Hardened prototype pollution safety by verifying property descriptors and skipping non-enumerable properties.
114
+ - Streamlined clone paths with `globalThis.structuredClone` and robust fallback handling.
115
+ - **`getElement` / `getElementItem` / `getElementOrWindow` / `isElementVisible`**:
116
+ - Extended `ElementOrWindow` type union to include `SVGElement` and generic `Element`.
117
+ - Hardened SSR safety with `isDomRuntime()` guards and safe fallbacks across DOM queries.
118
+ - Expanded unit tests and updated Storybook documentation.
119
+ - **`setElementItem`**:
120
+ - Decomposed into modular sub-utilities (`setElementItemStyle`, `setElementItemAttribute`, `setElementItemProperty`) while maintaining full backward-compatible API.
121
+ - **`CookieStorage` / `DataStorage` / `ServerStorage`**:
122
+ - `CookieStorage`: added SameSite `'none'` with automatic `Secure` per RFC 6265bis, CHIPS `Partitioned` support, control character sanitization, and exact return type inference via `CookieStorageGet<T, D>`.
123
+ - `DataStorage`: exported `DataStorageGet<T, D>` conditional type, isolated keys by process prefix, and protected `JSON.parse` with `isObjectNotArray`.
124
+ - `ServerStorage`: refactored internal storage to use null-prototype dictionaries, integrated `executeFunction`, and hardened hydration traversal.
125
+ - **`ErrorCenter` / `ErrorCenterHandler` / `ErrorCenterInstance`**:
126
+ - Added lifecycle unsubscription and cleanup methods (`remove`, `removeHandler`, `removeCallback`, `reset`).
127
+ - Added `getHandler(): ErrorCenterHandler` for direct handler access.
128
+ - Harmonized `group?: ErrorCenterGroup` typing across all methods.
129
+ - **`GeoInstance`**:
130
+ - Refactored as a lightweight composite layer delegating to `GeoLocation`, `GeoList`, and `GeoTimezone`, maintaining 100% backward compatibility.
131
+ - **Core Utilities**:
132
+ - `addTagHighlightMatch`: added `shouldRemoveTag` option and collision-resistant unique markers.
133
+ - `anyToString`: optimized options and string coercion.
134
+ - `isFilled`: hardened for empty tokens, `Date` instances, and prototype-less objects.
135
+ - `isNull`: refined TypeScript type predicate narrowing behavior.
136
+ - `getLast`: optimized array and object retrieval with strict return type inference.
137
+ - `encodeAttribute`: added fast-path check and non-string primitive support.
138
+ - `escapeExp`: supported numbers and nullish values safely.
139
+ - `capitalize`: enforced single unified signature without overloads (`T extends string ? Capitalize<T> : string`).
140
+ - `getElementSafeScript`: integrated `encodeAttribute` for robust XSS/injection protection and widened `id` to `string | number`.
141
+ - `getHydrationData`: supported numeric script IDs and nullish coalescing.
142
+ - `blobToBase64`: relaxed parameter typing to `Blob | null | undefined`.
143
+ - **Documentation & Tests**:
144
+ - Synchronized Storybook documentation across English, Russian, and Vietnamese (`.en.mdx`, `.ru.mdx`, `.vi.mdx`).
145
+ - Comprehensive unit test expansion across all packages with 100% passing test suites.
146
+
147
+ ### Security
148
+ - **Prototype Pollution Guards**:
149
+ - Comprehensive protection across `forOwn`, `splice`, `replaceRecursive`, `copyObject`, `setElementItemProperty`, `getObjectByKeys`, and `transformation` against prototype pollution vectors (`__proto__`, `constructor`, `prototype`).
150
+ - **XSS & Injection Protection**:
151
+ - Hardened `getElementSafeScript` via `encodeAttribute` sanitization and precompiled regexes.
152
+ - Hardened cookie value sanitization in `CookieStorage` stripping control characters (`\r`, `\n`, `\0`, `;`).
153
+
154
+ ## [1.14.0] - 2026-10-23
155
+
156
+ ### Added
157
+ - **`isPrototypeKey`**:
158
+ - Added `isPrototypeKey(key: string): boolean` utility function to detect prototype pollution keys (`'__proto__'`, `'constructor'`, `'prototype'`).
159
+ - Exported `isPrototypeKey` in public library exports (`src/library.ts`).
160
+ - Added comprehensive unit test suite in `src/functions/__tests__/isPrototypeKey.test.ts`.
161
+ - Added multilingual Storybook documentation in English, Russian, and Vietnamese.
162
+ - Generated AI type definitions in `ai-types-list/functions/isPrototypeKey.d.ts`.
163
+ - **`toPascalCase`**:
164
+ - Added `toPascalCase(value?: string): string` utility function to convert kebab-case, snake_case, or camelCase strings to PascalCase.
165
+ - Exported `toPascalCase` in public library exports (`src/library.ts`).
166
+ - Added comprehensive unit test suite in `src/functions/__tests__/toPascalCase.test.ts`.
167
+ - Added multilingual Storybook documentation in English, Russian, and Vietnamese.
168
+ - Generated AI type definitions in `ai-types-list/functions/toPascalCase.d.ts`.
169
+ - **`UrlInstanceAbstract` Test Suite**:
170
+ - Added comprehensive unit test suite covering URL abstraction methods, query parsing, and pathname manipulation in `src/classes/__tests__/UrlInstanceAbstract.test.ts`.
171
+ - **Documentation**:
172
+ - Added multilingual Storybook documentation for `encodeLiteAttribute`, `getHydrationData`, `isPrototypeKey`, and `toPascalCase` across English, Russian, and Vietnamese (`src/storybook/functions/`).
173
+ - Synchronized default component and function parameters across all Storybook stories (`.en.mdx`, `.ru.mdx`, `.vi.mdx`).
174
+
175
+ ### Changed
176
+ - **`uint8ArrayToBase64`**:
177
+ - Optimized conversion with Node.js `Buffer.from()` fast-path.
178
+ - Added `globalThis.btoa` fallback for Web Workers and isolated runtime environments.
179
+ - Implemented 32KB chunking (`CHUNK_SIZE = 0x8000`) for large arrays to avoid call stack limits in `String.fromCharCode.apply`.
180
+ - Added modern runtime support for native `Uint8Array.prototype.toBase64` when available.
181
+ - Extracted local `BufferType` interface and eliminated all `any` usages.
182
+ - **`transformation`**:
183
+ - Added generic type parameter inference: `transformation<T = unknown>(value: unknown, isFunctionCheck?: boolean): T`.
184
+ - Added balanced JSON bracket validation (`{...}`, `[...]`) before parsing to prevent unnecessary exceptions on non-JSON strings.
185
+ - Integrated prototype pollution guard via `isPrototypeKey`, skipping dangerous keys (`__proto__`, `constructor`, `prototype`).
186
+ - Renamed parameter `isFunction` to `isFunctionCheck` and modernized window lookup using `hasKey`, `isString`, and `isFunction`.
187
+ - **`copyObject`**:
188
+ - Added modern fast-path using native `globalThis.structuredClone` with safe fallback to `JSON.parse(JSON.stringify(value))` for non-cloneable objects.
189
+ - **`writeClipboardData`**:
190
+ - Added robust fallback `copyByExecCommand` using a hidden temporary `textarea` element created via `createElement` when `navigator.clipboard` is unavailable or fails.
191
+ - Integrated centralized error logging via `ErrorCenter.on` (`group: 'clipboard'`, `code: 'error'`).
192
+ - **`toDate`**:
193
+ - Normalized ISO-8601 UTC date formatting (`YYYY-MM-DDTHH:mm:ss.sssZ`).
194
+ - Precompiled static regular expressions for date parts to eliminate regex compilation overhead.
195
+ - Hardened string date parsing with bounds validation and fallback handling.
196
+ - **`toCamelCase` / `toCamelCaseFirst` / `toKebabCase`**:
197
+ - Precompiled regular expressions into static constants (`REGEXP_INVALID_CHARS`, `REGEXP_SEPARATORS`, `REGEXP_ACRONYMS`, `REGEXP_CAMEL_BOUNDARY`, `REGEXP_FIRST_CHAR`, `REGEXP_TRAILING_DASHES`).
198
+ - Added support for `snake_case` word boundaries, dots, and acronym normalization.
199
+ - Hardened nullish boundary checks for `null` and `undefined`.
200
+ - **`encodeAttribute` / `encodeLiteAttribute`**:
201
+ - Precompiled static regular expressions (`REGEXP_SPECIAL_CHARACTERS`, `REGEXP_SPECIAL_CHARACTERS_LITE`).
202
+ - Replaced `String(text)` with `toString(text)` helper for safe nullish coercion.
203
+ - Standardized constants naming to `SPECIAL_CHARACTERS` and `SPECIAL_CHARACTERS_LITE`.
204
+ - **`escapeExp`**:
205
+ - Precompiled static regular expression `REGEXP_SPECIAL_CHARS`.
206
+ - Guaranteed escaping of hyphen (`-`) characters in character class expressions.
207
+ - **`executeFunction`**:
208
+ - Modernized signature with generic argument inference: `executeFunction<T, Args extends unknown[] = unknown[]>(callback: T | FunctionArgs<never, T> | ((...args: Args) => T), ...args: Args): T`, eliminating all `any` types.
209
+ - **`getObjectByKeys`**:
210
+ - Protected against prototype pollution using `!isPrototypeKey(key) && hasKey(data, key)` before copying properties.
211
+ - Replaced `Record<string, any>` with `Record<string, unknown>`.
212
+ - **`getItemByPath`**:
213
+ - Hardened nested path resolution when intermediate properties are missing or undefined.
214
+ - Replaced `Record<string, any>` with `Record<string, unknown>`.
215
+ - **`toArray`**:
216
+ - Replaced `Array.isArray` with `isArray` helper and refined generic signature to `T extends unknown[] ? T : [T]`.
217
+ - **`isFunction` / `isObject` / `isObjectNotArray`**:
218
+ - Replaced `any` with strongly typed constructs: `FunctionAnyType` and `ObjectItem`.
219
+ - Replaced `Array.isArray` with `isArray` helper in `isObjectNotArray`.
220
+ - **`isString`**:
221
+ - Streamlined type predicate parameter: `isString(value: unknown): value is string`.
222
+ - **`isSelected` / `isSelectedByList`**:
223
+ - Supported intelligent numeric string comparison in arrays (matching numeric strings like `'42'` with number `42`).
224
+ - Cleaned up redundant type assertions and replaced `Array.isArray` with `isArray`.
225
+ - **`isNumber`**:
226
+ - Refined return type predicate to `value is number | string`.
227
+ - Enhanced regular expression with sign support (`[+-]?`) and trimmed input whitespace.
228
+ - **`isInput`**:
229
+ - Added isomorphic SSR guard via `isDomRuntime()`.
230
+ - Added `includeDisabled?: boolean` option to optionally include disabled and readonly form elements.
231
+ - Refined type predicate to `target is HTMLElement`.
232
+ - **`isFloat`**:
233
+ - Implemented finite float regular expression validation and accepted `value: unknown`.
234
+ - **`isFilled`**:
235
+ - Replaced `Object.keys()` with `for...in` loop and `hasKey` check, optimizing performance and memory footprint.
236
+ - Replaced `Array.isArray` with `isArray`.
237
+ - **`isEnter`**:
238
+ - Modernized keyboard event key check and added SSR safety with `isDomRuntime()`.
239
+ - **`isElementVisible`**:
240
+ - Improved DOM visibility detection with `isDomRuntime()` check and computed styles verification.
241
+ - **`isDifferent`**:
242
+ - Enhanced deep equality comparisons across complex nested structures and primitives.
243
+ - Replaced `forEach` with a fast breakable `for...in` loop.
244
+ - **`goScroll` / `goScrollSmooth` / `goScrollTo`**:
245
+ - Added isomorphic SSR guards (`isDomRuntime()`).
246
+ - Replaced manual `typeof === 'object'` and `typeof === 'function'` checks with `isObject` and `isFunction` helpers.
247
+ - Improved smooth scrolling fallback logic and bounding rect calculations.
248
+ - **`replaceComponentName`**:
249
+ - Converted to standard function declaration with explicit `string | undefined` return type.
250
+ - **`ApiInstance`**:
251
+ - Ensured SSR safety when handling `FormData` with `typeof FormData !== 'undefined'` in `getBody` and `getBodyForGet`.
252
+ - Enhanced `getBodyForGet` to distinguish between `FormData` and object query parameters.
253
+ - **`apiTypes`**:
254
+ - Documented global caching behavior in `ApiFetch` (`cache`, `enableClientCache`, `cacheId`) clarifying user-independent request scope.
255
+ - Expanded `ApiErrorStorageItem.code` type from `string | undefined` to `string | number | undefined`.
256
+ - **`getElementSafeScript`**:
257
+ - Precompiled static regular expressions `REGEXP_DOUBLE_QUOTE` and `REGEXP_CLOSING_SCRIPT`.
258
+ - **Local Type Extraction**:
259
+ - Extracted inline types to scoped local types across all utility functions (`blobToBase64`, `copyObject`, `encodeAttribute`, `escapeExp`, `executeFunction`, `forEach`, `getElementSafeScript`, `getObjectByKeys`, `getRandomText`, `goScrollSmooth`, `goScrollTo`, `isDomRuntime`, `isFilled`, `isObjectNotArray`, `isSelectedByList`, `replaceComponentName`, `sortList`, `splice`, `strSplit`, `toArray`, `toCamelCase`, `transformation`, `uint8ArrayToBase64`, `writeClipboardData`) maintaining clean encapsulation without leaking unexported types.
260
+ - **Tests & AI Documentation**:
261
+ - Comprehensive unit test expansion across all 185 test suites (3271 tests passing with 100% coverage).
262
+ - Synchronized bilingual Storybook documentation across English, Russian, and Vietnamese.
263
+ - Refreshed AI type definitions and search keywords in `ai-types-list/`.
264
+
265
+ ### Fixed
266
+ - **`toNumberByMax`**:
267
+ - Fixed falsy max value bug: correctly handles `max = 0` instead of falling back to default max value.
268
+ - **`toNumberPositive`**:
269
+ - Delegated number parsing to `toNumber` and enforced `> 0` check with fallback.
270
+ - **`toNumber`**:
271
+ - Eliminated variable shadowing and improved numeric parsing for edge cases.
272
+ - **`setElementItem`**:
273
+ - Prevented prototype pollution by validating property keys against `isPrototypeKey`.
274
+ - Fixed boolean and ARIA attribute handling: formatted `aria-*` attributes as `'true'`/`'false'`, set empty string for true boolean attributes, and removed attributes when value is `false` or `null`.
275
+ - **`sortTypes`**:
276
+ - Eliminated `any` in `SortFunction` by replacing with `Record<string, unknown>`.
277
+ - **`ApiStatus`**:
278
+ - Replaced `in` operator checks with `hasKey` helper in `setLastResponse` to prevent `TS2638` type narrowing errors.
279
+ - **`BroadcastMessage`**:
280
+ - Added fallback in `getBroadcastName` to guarantee `string` return type (`TS2322`).
281
+
282
+ ## [1.13.0] - 2026-10-18
283
+
284
+ ### Added
285
+ - **`hasKey`**:
286
+ - Added `hasKey<K extends PropertyKey, T extends object = Record<K, unknown>>(object: unknown, key: K): object is T & Record<K, unknown>` utility function to safely check for own object properties (`Object.prototype.hasOwnProperty`) with TypeScript type narrowing.
287
+ - Exported `hasKey` in public library exports (`src/library.ts`).
288
+ - Added comprehensive unit test suite in `src/functions/__tests__/hasKey.test.ts`.
289
+ - Added multilingual Storybook documentation in English, Russian, and Vietnamese.
290
+ - Generated AI type definitions in `ai-types-list/functions/hasKey.d.ts`.
291
+ - **`resetGetElementId`**:
292
+ - Added `resetGetElementId(): void` function to reset the registered SSR context listener back to `undefined`.
293
+ - **Type Definitions**:
294
+ - Exported `GetElementImageCallback` type for image `onload` and `onerror` event callback signatures.
295
+ - Exported `ResizeImageByMaxType` ('auto' | 'width' | 'height') type definition.
296
+
297
+ ### Changed
298
+ - **`executePromise`**:
299
+ - Enhanced type signature to accept `PromiseLike<T> | T` and generic arguments `Args extends unknown[]`, returning `Promise<Awaited<T>>` with zero `any`.
300
+ - Simplified asynchronous resolution with native `await`.
301
+ - **`ensureMaxSize`**:
302
+ - Refactored `file` parameter typing to `Uint8Array` / `BlobPart` with safe fallback to `blobToBase64` when image dimensions are within size limits or resizing is not required.
303
+ - Ensured reliable object URL revocation (`URL.revokeObjectURL`) in all execution branches (`onload`, `onerror`, and fallback).
304
+ - **`getElementImage`**:
305
+ - Added optional `onload` and `onerror` callbacks (`GetElementImageCallback`) for `HTMLImageElement` creation from string sources.
306
+ - Directly returns existing `HTMLImageElement` instances without re-wrapping.
307
+ - **`resizeImageByMax`**:
308
+ - Added explicit `maxSize > 0` validation guard and rounded dimensions (`Math.round`) for canvas scaling.
309
+ - Documented design rationale for returning `undefined` when resizing is unneeded or impossible to prevent unnecessary canvas re-encoding.
310
+ - **`applyTemplate`**:
311
+ - Refactored template macro matching with static precompiled regexes (`EXP_LIST_MACROS`, `EXP_TAG_MACROS`, `EXP_KEY_MACROS`, `EXP_CONTENT_MACROS`).
312
+ - Integrated `hasKey` for checking replacement object own properties, avoiding prototype pollution.
313
+ - Added string fast-path checks (`includes('[') || includes('{')`) before executing regex replacements.
314
+ - **`addTagHighlightMatch`**:
315
+ - Replaced inline tags with uppercase constants (`TAG_START`, `TAG_END`, `EXP_TAG`) and extracted tag helper functions (`getTagStart`, `getTagEnd`).
316
+ - Added `isSearchValid` helper to safely validate search strings and regular expressions.
317
+ - Added direct fast-path return when `shouldEscape` is `false`.
318
+ - **`getAttributes`**:
319
+ - Modernized attribute extraction to use standard `item.getAttributeNames()` and `item.getAttribute(name)` with `getAttributeNames in item` guard, eliminating deprecated `NamedNodeMap` iteration.
320
+ - **`forEach`**:
321
+ - Added overloaded TypeScript signatures for `readonly T[]`, `Set<T>`, `Map<K, V>`, and `Record<string, T>` collections with strongly typed keys (`ForEachKey<D>`).
322
+ - Optimized array and object iteration using standard `for` loops and `Object.keys()` instead of native `forEach` and `for...in`.
323
+ - **`frame`**:
324
+ - Added `timestamp: DOMHighResTimeStamp` parameter to `callback` and `next` functions.
325
+ - Passed `0` timestamp fallback in SSR/non-DOM environments.
326
+ - **`getObjectNoUndefined`**:
327
+ - Added overloads for `readonly V[]` and `Record<PropertyKey, unknown>` with strict types.
328
+ - Replaced `forEach` with `Object.entries()` and `Object.is()` comparison for exception value filtering.
329
+ - **`getElementId`**:
330
+ - Added `Window` support: assigning and retrieving ID directly on `document.body` when a `Window` object is passed.
331
+ - Extracted `SERVER_STORAGE_KEY` constant (`__ui:getElementId__`).
332
+ - Hardened context ID check with `!isNull(contextId) && contextId !== ''`.
333
+ - Added explicit `void` return type for `initGetElementId`.
334
+ - **`getElementItem`**:
335
+ - Renamed parameter `index` to `property` for clarity and consistency across element accessor functions.
336
+ - **`getElementSafeScript`**:
337
+ - Added generic type parameter `T = unknown` for data input.
338
+ - Added fallback `?? 'null'` when `JSON.stringify` returns `undefined`.
339
+ - **`getItemByPath`**:
340
+ - Hardened nested path resolution when intermediate properties are missing or undefined.
341
+ - **`getLast`**:
342
+ - Supported `readonly T[]` in value parameter type.
343
+ - Optimized object property access via `Object.keys()` without full value array allocations.
344
+ - **`getLength`**:
345
+ - Replaced `value: any` with `value: unknown` and `Array.isArray` with `isArray` helper.
346
+ - **`setElementItem`**:
347
+ - Extracted helper functions `setElementItemProperty` and `setElementItemBoolean`.
348
+ - Added support for CSS custom properties (`--*`) on style targets via `setProperty()`.
349
+ - Added direct `cssText` assignment when setting `'style'` with a string value.
350
+ - Used `Reflect.set` for safe element property assignment.
351
+ - **`createElement`**:
352
+ - Supported `Element | DocumentFragment` for `parentElement` parameter and `Node | null` for `referenceElement`.
353
+ - Replaced `typeof options === 'function'` with `isFunction(options)`.
354
+ - Documented `document.createElementNS` usage recommendation for SVG/MathML elements in `@remarks`.
355
+ - **`domContentLoaded`**:
356
+ - Added optional `isServer` parameter (default `true`) allowing callers to disable SSR fallback execution.
357
+ - Allowed calling without arguments to return a promise that resolves upon DOM readiness.
358
+ - **`anyToString`**:
359
+ - Added double `try...catch` fallback resolving `Object.prototype.toString.call(value)` when standard serialization fails.
360
+ - **`encodeAttribute` / `encodeLiteAttribute`**:
361
+ - Replaced `String(text)` with `toString(text)` helper for safe nullish coercion.
362
+ - Standardized constants naming to `SPECIAL_CHARACTERS` and `SPECIAL_CHARACTERS_LITE`.
363
+ - **`isDifferent`**:
364
+ - Replaced `forEach` with a fast breakable `for...in` loop.
365
+ - **Tests & AI Documentation**:
366
+ - Overhauled and expanded unit test suites across all core utility functions (`addTagHighlightMatch`, `anyToString`, `applyTemplate`, `arrFill`, `blobToBase64`, `capitalize`, `createElement`, `domContentLoaded`, `encodeAttribute`, `encodeLiteAttribute`, `ensureMaxSize`, `escapeExp`, `executePromise`, `forEach`, `frame`, `getArrayHighlightMatch`, `getAttributes`, `getColumn`, `getElementId`, `getElementImage`, `getElementItem`, `getElementSafeScript`, `getHydrationData`, `getItemByPath`, `getLast`, `getLength`, `getObjectNoUndefined`, `getSeparatingSearchExp`, `hasKey`, `resizeImageByMax`, `setElementItem`, `toString`) following zero-`any` and edge-case boundary testing standards.
367
+ - Updated Storybook documentation for `executePromise`, `frame`, `getElementImage`, and `hasKey` across English, Russian, and Vietnamese.
368
+ - Refreshed AI type definitions and search keywords in `ai-types-list/`.
369
+
370
+ ### Fixed
371
+ - **`getSeparatingSearchExp`**:
372
+ - Fixed word matching ordering by sorting terms by descending length (`b.length - a.length`), ensuring longer terms match before shorter substrings.
373
+ - Fixed empty or whitespace-only search returning `/^/` (which falsely matched empty lines) by returning a never-matching regex `/(?!)/`.
374
+ - **`getArrayHighlightMatch`**:
375
+ - Guaranteed global flag (`g`) on regular expressions via `toGlobalExp`.
376
+ - Fixed potential infinite loop on zero-width matches by manually advancing `lastIndex`.
377
+ - **`getHydrationData`**:
378
+ - Replaced `typeof document !== 'undefined'` with isomorphic helper `isDomRuntime()`.
379
+ - Added `script.tagName === 'SCRIPT'` tag validation guard.
380
+ - Wrapped `script.remove()` in a `finally` block to guarantee DOM cleanup even on JSON parse errors.
381
+ - **`setElementItem`**:
382
+ - Fixed boolean and ARIA attribute handling: formatted `aria-*` attributes as `'true'`/`'false'`, set empty string for true boolean attributes, and removed attributes when value is `false` or `null`.
383
+ - **`capitalize`**:
384
+ - Fixed capitalization of astral plane Unicode characters / surrogate pairs (code points > 0xFFFF) by extracting code-point-aware character slices.
385
+ - **`escapeExp`**:
386
+ - Fixed regex escaping to escape hyphen (`-`) characters in character class expressions.
387
+ - **`blobToBase64`**:
388
+ - Wrapped conversion logic in a safe `try...catch` block to return `undefined` on unhandled FileReader or corrupt blob errors.
389
+
390
+ ## [1.12.0] - 2026-10-14
391
+
392
+ ### Added
393
+ - **`skipFrame`**:
394
+ - Added `skipFrame(callback?: () => T | Promise<T>, count: number = 1): Promise<T | void>` utility function to wait for or skip a specified number of animation frames (`requestAnimationFrame`) before executing a callback or resolving.
395
+ - Added SSR-safe resolution: immediately resolves in non-DOM environments (`!isDomRuntime()`) without invoking `requestAnimationFrame`.
396
+ - Added comprehensive unit test suite in `src/functions/__tests__/skipFrame.test.ts`.
397
+ - Added multilingual Storybook documentation across English, Russian, and Vietnamese.
398
+
399
+ ### Changed
400
+ - **Dependencies**:
401
+ - Updated `@dxtmisha/media` dependency to `>=0.8.1`.
402
+ - **Tests & AI Documentation**:
403
+ - Improved hydration test mocks in `getHydrationData.test.ts`.
404
+ - Updated AI type declarations and package descriptions.
405
+
5
406
  ## [1.11.1] - 2026-10-04
6
407
 
7
408
  ### Changed
package/ai-description.md CHANGED
@@ -1,8 +1,8 @@
1
- This package provides a comprehensive isomorphic foundational toolkit containing utilities for API communication, request lifecycle handling, storage management, and DOM manipulation. It includes robust internationalization and localization systems for date-time calculations, units, currencies, phone masks, and multi-language translations, alongside SEO meta tag generation and URL state synchronization. An AI assistant should study this package when implementing client-server data fetching with SSR hydration, browser storage persistence, localized data formatting, text search matching, or DOM event lifecycle control.
1
+ This package provides a comprehensive isomorphic foundation for web applications, supplying robust API request handling with SSR hydration, multi-layer client and server storage, internationalization engines, and browser lifecycle utilities. An AI assistant must study this package when implementing client-server data synchronization, localized formatting for dates, currencies, and measurement units, or managing URL query and cookie states across SSR and client runtimes. It is equally essential for executing multi-column search filtering with text highlighting, managing DOM events, processing images, and configuring SEO metadata.
2
2
 
3
- Key Capabilities: HTTP Client, SSR Hydration, API Caching, Request Interceptors, Cross-Tab Messaging, Cookie Management, Local Storage, Session Storage, In-Memory Caching, Date Manipulation, Locale Formatting, Currency Formatting, Unit Conversion, Phone Number Masking, Flag Icons, Translation Management, Meta Tag Management, Open Graph SEO, Twitter Cards, URL Query Management, URL Hash Routing, Search Highlighting, List Sorting, DOM Event Management, Global Loading State, Resumable Timer, Clipboard Utilities, Image Resizing, Scroll Control, Type Checking Utilities
3
+ Key Capabilities: HTTP Client, API Interceptors, SSR Hydration, Server Storage, Cookie Management, Web Storage, Internationalization, Calendar Calculations, Localized Formatting, Unit Conversion, Phone Masking, Localization Translation, SEO Metadata, Open Graph Tags, URL State Management, Search Filtering, Match Highlighting, DOM Event Management, Image Resizing, Clipboard Access, Web Share Integration, Error Dispatching, Icon Management, Viewport Scrolling
4
4
  ## Mandatory Rules
5
5
  You MUST evaluate whether your task relates to any of the following topics (even if not working directly with this package). If related material is present, you are strictly obligated to read and study the corresponding file before proceeding:
6
- - 'node_modules/@dxtmisha/functional-basic/ai-resources/api-reference.md': Provides usage guidelines and API references for HTTP requests, caching, storage, localization, and DOM utility functions.
6
+ - 'node_modules/@dxtmisha/functional-basic/ai-resources/api-reference.md': Comprehensive reference and examples for HTTP client, caching, storage, localization, and core utilities.
7
7
  - 'node_modules/@dxtmisha/functional-basic/ai-resources/design-config.md': Rules and schema for configuring design systems, TypeScript declaration scanning, AI generation, and package settings.
8
8
  - 'node_modules/@dxtmisha/functional-basic/ai-resources/error-center.md': Standards and APIs for centralized error handling, routing exceptions via ErrorCenter without direct console logging.
package/ai-doc.md CHANGED
@@ -2,7 +2,7 @@ Framework-agnostic utility library. **Vue developers MUST search `@dxtmisha/func
2
2
 
3
3
  ## Coding Standards & Conventions
4
4
 
5
- - **Class Structure**: Properties/Variables (`public`->`protected`->`private`) -> Constructor -> Public Methods -> Protected Methods -> Private Methods. Within each method group, follow order: 1) `get` (getters), 2) `set` (setters), 3) `is...`, 4) `has...`, 5) `get...`, 6) `set...`, 7) `add...`, 8) `remove...`, 9) `update...`, 10) `reset...`, 11) remaining methods. Within each subgroup, methods are grouped semantically by logical pairs and rules (e.g., `min` / `max`, `width` / `height`, `x` / `y` / `z`), and remaining methods are sorted alphabetically.
5
+ - **Class Structure**: Properties/Variables (`public`->`protected`->`private`) -> Constructor -> Computed/Reactive Properties (`computed` and similar reactive fields are ALWAYS placed after the constructor) -> Public Methods -> Protected Methods -> Private Methods. Within each method group, follow order: 1) `get` (getters), 2) `set` (setters), 3) `is...`, 4) `has...`, 5) `get...`, 6) `set...`, 7) `add...`, 8) `remove...`, 9) `update...`, 10) `reset...`, 11) remaining methods. Within each subgroup, methods are grouped semantically by logical pairs and rules (they always go in pairs, e.g., `min` / `max`, `width` / `height`, `x` / `y` / `z`), and remaining methods are sorted alphabetically.
6
6
  - **Style/Types**: `PascalCase` classes, `camelCase` methods/props, `UPPER_SNAKE_CASE` constants. No `any` (use `unknown`/generics). Explicit return types for ALL methods. Export all interfaces. Type files: `*Types.ts`. Use `@effect/schema` for schemas.
7
7
  - **SSR Safety**: Isomorphic code. Do NOT store request state in globals. Use `isDomRuntime()` before `window`/`document`. Use `ServerStorage.get('key', () => new Class())` for request-isolated singletons.
8
8
  - **Utility & Primitive Functions**: ALWAYS use primitive helper functions from this package (e.g. `isFunction`, `executeFunction`, `isFilled`, `isObject`, `isString`, `isArray`, etc.) instead of writing custom inline checks or conditions.
@@ -15,7 +15,7 @@
15
15
  "uri": "@dxtmisha/functional-basic/ai-resources/api-reference.md",
16
16
  "name": "Functional Basic API Reference (@dxtmisha/functional-basic)",
17
17
  "mimeType": "text/markdown",
18
- "description": "Provides usage guidelines and API references for HTTP requests, caching, storage, localization, and DOM utility functions."
18
+ "description": "Comprehensive reference and examples for HTTP client, caching, storage, localization, and core utilities."
19
19
  },
20
20
  {
21
21
  "uri": "@dxtmisha/functional-basic/ai-resources/design-config.md",
@@ -12,6 +12,19 @@ const updated = await Api.post<User>({ path: 'profile', request: { name: 'New' }
12
12
  await ApiCache.set('k', { a: 1 }, 60000); const cache = await ApiCache.get<{a: number}>('k');
13
13
  ```
14
14
 
15
+ ### Global Response Caching (`ApiCache` & `ApiFetch.cache`)
16
+ - **Intentional Global Scope (User-Independent)**: `ApiCache` (and the `cache?: number` option in `ApiFetch`) is **intentionally a global, shared cache** across the application process (and across all SSR requests when backed by memory or Nitro storage via `initPluginApiCache`).
17
+ - **Use Case**: Enable `cache` (TTL in seconds) **only for public, user-independent requests** (e.g., reference dictionaries, static configurations, public catalogs) whose responses do not depend on the current user or session.
18
+ - **Warning**: Do **NOT** use `cache` on personalized or user-specific endpoints. If a public endpoint varies by external context (e.g., locale or tenant) not present in `request`, pass an explicit `cacheId` in `ApiFetch` to segment the cache key:
19
+ ```typescript
20
+ const countries = await Api.get({
21
+ path: 'public/countries',
22
+ cache: 3600, // Cached globally for 1 hour (in seconds)
23
+ cacheId: Geo.getLocation(), // Optional custom discriminator for global cache key
24
+ enableClientCache: true // Optional: also enable in browser runtime (SSR is enabled by default when `cache` is set)
25
+ });
26
+ ```
27
+
15
28
  ### Error Responses & Return Types (`ApiData<T>`)
16
29
 
17
30
  When an error occurs during an API call, `Api` behaves differently depending on whether it is an HTTP response error or a network/runtime failure:
@@ -91,6 +104,9 @@ const srv = ServerStorage.get('svc', () => new Svc()); // SSR isolated
91
104
  ```
92
105
 
93
106
  ## Geolocation, Formatting & Localization
107
+
108
+ `TranslateInstance` groups queued translation codes by the language, location, and resolved API path captured when they were requested. API URL placeholders are resolved before the batching delay. File selection, cache writes, and asynchronous results retain that locale even if it changes during the delay or loading. `TranslateFile.getList(location?, language?)` and `isFile(location?, language?)` accept an explicit locale; omitted values use the current providers. File lookup still prefers location, then language, then `global`.
109
+
94
110
  ```typescript
95
111
  import { Geo, GeoIntl, GeoFlag, GeoPhone } from '@dxtmisha/functional-basic';
96
112
  const country = Geo.getCountry(); const lang = Geo.getLanguage(); Geo.set('en-US');