@dxtmisha/functional-basic 1.6.2 → 1.6.4

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.
Files changed (2) hide show
  1. package/ai-doc.md +74 -279
  2. package/package.json +1 -1
package/ai-doc.md CHANGED
@@ -1,346 +1,141 @@
1
- This is the basic functional library (@dxtmisha/functional-basic). It contains framework-agnostic algorithms, utilities, and classes.
1
+ # @dxtmisha/functional-basic Reference
2
2
 
3
- ATTENTION FOR VUE ENVIRONMENT:
4
- If you are developing in Vue, ALWAYS look for the required functionality (composables, reactive wrappers) inside the `@dxtmisha/functional` library FIRST.
5
- And ONLY if there is no reactive or Vue-specific analog there, you may use the functionality directly from this library (@dxtmisha/functional-basic).
3
+ Framework-agnostic utility library. **Vue developers MUST search `@dxtmisha/functional` first**; use this ONLY if no reactive/Vue-specific analog exists.
6
4
 
7
- =============================================================================
8
- CLASS STRUCTURE & CODING STANDARDS (RULES FOR AI)
9
- =============================================================================
10
-
11
- To maintain consistency and high industrial quality across the dxt-ui codebase, all TypeScript classes inside `@dxtmisha/functional-basic` must strictly adhere to the following rules regarding structure, member ordering, and styles.
12
-
13
- 1. ORDER OF MEMBERS WITHIN A CLASS
14
- Members in every class MUST be ordered in the following sequence:
15
-
16
- A. Class Properties / Member Variables:
17
- - Placed at the very top of the class body.
18
- - Ordered by visibility: Public first, then Protected, and Private last.
19
- - Within each visibility level, group by logical connection or alphabetically.
20
- - Initialize default values directly on declaration when possible.
21
-
22
- B. Constructor:
23
- - Placed immediately after all property declarations.
24
- - Parameter properties (e.g., `protected url: string`) are allowed to simplify declaration.
25
-
26
- C. Public Methods:
27
- - Placed after the constructor.
28
- - Grouped logically:
29
- 1. Getters, checkers, and status-check methods (e.g., `is*`, `get*`).
30
- 2. Setters and configuration methods (e.g., `set*`).
31
- 3. Core executors and action methods (e.g., `request()`, `fetch()`, `show()`).
32
-
33
- D. Protected Methods:
34
- - Placed after all public methods.
35
- - Contain internal utility and helper logic accessible to subclasses.
36
-
37
- E. Private Methods:
38
- - Placed at the very end of the class.
39
- - Strict encapsulation of internal logic.
40
-
41
- 2. CODING & STYLE CONVENTIONS
42
- - Naming:
43
- * Classes: PascalCase (e.g., `LoadingInstance`).
44
- * Methods & Properties: camelCase (e.g., `registrationEvent`, `registrationList`).
45
- * Constants inside files: UPPER_SNAKE_CASE (e.g., `LOADING_EVENT_NAME`).
46
- - TypeScript Safety:
47
- * Never use `any`. Use generic parameters or `unknown` if the type is dynamic/undefined.
48
- * Explicitly declare return types for ALL public, protected, and private methods (including `void`).
49
- * Use interfaces/types to define structural contracts for complex inputs and outputs.
50
- - SSR Isolation (Server-Side Rendering):
51
- * The library must be fully isomorphic and safe for SSR.
52
- * Avoid storing request-specific state in global/static class properties directly.
53
- * Use `ServerStorage.get('key', () => new Instance())` for request-isolated singletons.
54
- * Use `isDomRuntime()` checks before accessing browser-only APIs like `window`, `document`, or `location`.
5
+ ---
55
6
 
56
- 3. TYPES, INTERFACES, AND ENUMS
57
- - Location: All types, interfaces, and enums must be located in the `src/types` directory if it exists in the project. If the `src/types` directory does not exist, they must be defined in the same file where they are used.
58
- - Export: All types, interfaces, and enums must be explicitly exported.
59
- - API Types/Schemas: All types and interfaces for working with APIs must be defined/generated using the `@effect/schema` library if it is present in the project's dependencies (if the project is a monorepo, also check root dependencies).
7
+ ## Coding Standards & Class Structure
60
8
 
61
- =============================================================================
62
- DEVELOPER GUIDE: USING `@dxtmisha/functional-basic` AS A LIBRARY
63
- =============================================================================
9
+ ### 1. Class Member Order
10
+ 1. **Properties/Variables**: Top of class, ordered by visibility (`public` -> `protected` -> `private`). Initialize inline if possible.
11
+ 2. **Constructor**: Follows properties. Parameter properties (e.g. `protected url: string`) allowed.
12
+ 3. **Public Methods**:
13
+ 1. Getters, checkers, status methods (`is*`, `get*`).
14
+ 2. Setters & configuration (`set*`).
15
+ 3. Core executors & actions (`request()`, `fetch()`, `show()`).
16
+ 4. **Protected Methods**: Internal helpers for subclasses.
17
+ 5. **Private Methods**: Internal helper logic at the very bottom.
64
18
 
65
- This section contains instructions and code guidelines for AI models on how to import and use the framework-agnostic utilities, classes, and helper functions provided by this library in client packages or applications.
19
+ ### 2. Style & Type Conventions
20
+ - **Naming**: Classes = `PascalCase`, Methods/Properties = `camelCase`, Constants = `UPPER_SNAKE_CASE`.
21
+ - **TypeScript**: No `any` (use `unknown`/generics). Explicit return types on ALL methods (including `void`). Export all types/interfaces. Suffix type files with `Types` (e.g., `*Types.ts`). Use `@effect/schema` for API schemas if present.
22
+ - **SSR Safety**: Isomorphic code. Do not store request-specific state in static/global variables. Use `isDomRuntime()` before accessing `window`/`document`/`location`. Use `ServerStorage.get(key, () => new Instance())` for request-isolated singletons.
66
23
 
67
24
  ---
68
25
 
69
- ### 1. HTTP Client (`Api` and `ApiInstance`)
70
-
71
- The library provides both a static global class `Api` and an instantiable `ApiInstance` wrapper around the native `fetch` API. They support cancellation, caching, interceptors, error handling, and loading states.
26
+ ## API Reference & Examples
72
27
 
73
- #### Configuration
28
+ ### 1. HTTP Client (`Api`, `ApiInstance`, `ApiCache`)
74
29
  ```typescript
75
- import { Api } from '@dxtmisha/functional-basic';
30
+ import { Api, ApiCache } from '@dxtmisha/functional-basic';
76
31
 
77
- // Set base origin and API path
32
+ // Config
78
33
  Api.setOrigin('https://api.example.com');
79
34
  Api.setUrl('/api/v1');
80
-
81
- // Setup global request defaults (e.g., query params sent with every request)
82
35
  Api.setRequestDefault({ client: 'web' });
36
+ Api.setHeaders(() => ({ Authorization: `Bearer ${localStorage.getItem('token') || ''}` }));
83
37
 
84
- // Setup global headers (can pass a callback for dynamic values)
85
- Api.setHeaders(() => ({
86
- Authorization: `Bearer ${localStorage.getItem('token') || ''}`,
87
- }));
88
- ```
38
+ // Interceptors
39
+ Api.setPreparation(async (fetchOpts) => { if (fetchOpts.auth) fetchOpts.headers['X-Auth'] = '1'; });
40
+ Api.setEnd(async (res, fetchOpts) => res.status === 401 ? { reset: true } : {});
89
41
 
90
- #### Making Requests
91
- ```typescript
92
- // Simple request: defaults to GET
93
- const users = await Api.request<User[]>('users');
94
-
95
- // Explicit methods
42
+ // Requests
43
+ const users = await Api.request<User[]>('users'); // default GET
96
44
  const profile = await Api.get<User>({ path: 'profile' });
97
- const updated = await Api.post<User>({
98
- path: 'profile',
99
- request: { name: 'New Name' }, // Request payload
100
- });
101
- ```
102
-
103
- #### Interceptors (Preparation and End Lifecycle Hooks)
104
- ```typescript
105
- // Preparation hook: runs before fetch executes
106
- Api.setPreparation(async (apiFetch) => {
107
- // Can mutate apiFetch settings or inject headers
108
- if (apiFetch.auth) {
109
- apiFetch.headers = { ...apiFetch.headers, 'X-Auth-Required': 'true' };
110
- }
111
- });
112
-
113
- // End hook: runs after response is received
114
- Api.setEnd(async (response, apiFetch) => {
115
- if (response.status === 401) {
116
- // Perform token refresh or trigger sign-out
117
- return { reset: true }; // Resets request/attempts or signals failure
118
- }
119
- return {};
120
- });
121
- ```
122
-
123
- #### Local caching with `ApiCache`
124
- ```typescript
125
- import { ApiCache } from '@dxtmisha/functional-basic';
45
+ const updated = await Api.post<User>({ path: 'profile', request: { name: 'New' } });
126
46
 
127
- // Cache responses client-side
128
- await ApiCache.set('custom-cache-key', data, 60000); // age in ms
129
- const cached = await ApiCache.get<MyDataType>('custom-cache-key');
47
+ // Cache
48
+ await ApiCache.set('key', { data: 1 }, 60000); // ms age
49
+ const cached = await ApiCache.get<{ data: number }>('key');
130
50
  ```
131
51
 
132
- ---
133
-
134
52
  ### 2. State & Storage Management
135
-
136
- The library features SSR-safe classes to manipulate `localStorage`/`sessionStorage`, cookies, and server-side contexts.
137
-
138
- #### `DataStorage` (localStorage / sessionStorage)
139
- Safely wraps storage with optional namespace prefixes, fallback defaults, and expiration cache.
140
53
  ```typescript
141
- import { DataStorage } from '@dxtmisha/functional-basic';
54
+ import { DataStorage, CookieStorage, Cookie, ServerStorage } from '@dxtmisha/functional-basic';
142
55
 
143
- // Set global namespace prefix to avoid storage collisions
56
+ // DataStorage (localStorage/sessionStorage)
144
57
  DataStorage.setPrefix('my_app_');
145
-
146
- // Instantiate a persistent storage item (sessionStorage if 2nd arg is true)
147
- const userStorage = new DataStorage<{ id: string }>('user_session', false);
148
-
149
- // Save value
58
+ const userStorage = new DataStorage<{ id: string }>('user_session', false); // true for sessionStorage
150
59
  userStorage.set({ id: '123' });
151
-
152
- // Get value (with default value fallback and optional cache limit in ms)
153
- const user = userStorage.get({ id: 'guest' });
154
-
155
- // Remove item
60
+ const user = userStorage.get({ id: 'guest' }); // fallback default
156
61
  userStorage.remove();
157
- ```
158
62
 
159
- #### `CookieStorage` & `Cookie`
160
- Standard cookie manager.
161
- ```typescript
162
- import { CookieStorage, Cookie } from '@dxtmisha/functional-basic';
163
-
164
- // Global Cookie usage
63
+ // Cookies
165
64
  CookieStorage.set('theme', 'dark', { age: 31536000, secure: true, sameSite: 'lax' });
166
65
  const theme = CookieStorage.get<string>('theme', 'light');
167
66
  CookieStorage.remove('theme');
168
67
 
169
- // Instance-based Cookie manager
170
68
  const tokenCookie = new Cookie<string>('auth_token');
171
69
  tokenCookie.set('xyz123', { secure: true });
172
70
  const token = tokenCookie.get();
173
- ```
174
-
175
- #### `ServerStorage` (SSR Request-Isolated Storage)
176
- Used to share and isolate singleton states safely across concurrent asynchronous server-side render requests.
177
- ```typescript
178
- import { ServerStorage } from '@dxtmisha/functional-basic';
179
71
 
180
- // Fetch or create a request-isolated instance singleton
181
- const myServiceInstance = ServerStorage.get('myService', () => new MyService());
72
+ // SSR Request-Isolated Storage
73
+ const myService = ServerStorage.get('myService', () => new MyService());
182
74
  ```
183
75
 
184
- ---
185
-
186
- ### 3. Geolocation & Localization (`GeoIntl`, `Geo`, `GeoFlag`, `GeoPhone`)
187
-
188
- Standardizes localization using the native browser/Node `Intl` API.
189
-
190
- #### `Geo`
191
- Used to track and modify country, language, standard, and timezone information.
76
+ ### 3. Geolocation & Localization
192
77
  ```typescript
193
- import { Geo } from '@dxtmisha/functional-basic';
194
-
195
- // Get current geo details
196
- const currentCountry = Geo.getCountry(); // e.g., 'VN'
197
- const currentLang = Geo.getLanguage(); // e.g., 'vi'
78
+ import { Geo, GeoIntl, GeoFlag, GeoPhone } from '@dxtmisha/functional-basic';
198
79
 
199
- // Change locale configuration
80
+ // Geo state
81
+ const country = Geo.getCountry(); // e.g., 'VN'
82
+ const lang = Geo.getLanguage(); // e.g., 'vi'
200
83
  Geo.set('en-US');
201
- ```
202
-
203
- #### `GeoIntl`
204
- Used for localized numbers, currencies, percentages, dates, relative times, and file sizes.
205
- ```typescript
206
- import { GeoIntl } from '@dxtmisha/functional-basic';
207
84
 
85
+ // Formatters (Intl)
208
86
  const intl = new GeoIntl('en-US');
209
-
210
- // Numbers
211
- intl.number(123456.78); // '123,456.78'
212
-
213
- // Currencies
214
- intl.currency(99.99, 'USD'); // '$99.99'
215
-
216
- // File Sizes
217
- intl.sizeFile(1024 * 1024 * 5); // '5.00 MB'
218
-
219
- // Dates & Time
220
- intl.date(new Date(), 'date'); // 'Jun 18, 2026'
221
- intl.date(new Date(), 'time'); // '10:48 PM'
222
-
223
- // Relative time formatting
87
+ intl.number(123456.78); // '123,456.78'
88
+ intl.currency(99.99, 'USD'); // '$99.99'
89
+ intl.sizeFile(1024 * 1024 * 5); // '5.00 MB'
90
+ intl.date(new Date(), 'date'); // 'Jun 18, 2026'
91
+ intl.date(new Date(), 'time'); // '10:48 PM'
224
92
  intl.relative(new Date(Date.now() - 3600000)); // '1 hour ago'
93
+ intl.plural(3, 'apple|apples'); // '3 apples' ('one|other' or 'one|few|many|other')
225
94
 
226
- // Pluralization rules
227
- // Words are passed as a string delimited by '|' (e.g. 'one|other' or 'one|few|many|other')
228
- intl.plural(3, 'apple|apples'); // '3 apples'
229
- ```
230
-
231
- #### Country Flags (`GeoFlag`) and Phone Masks (`GeoPhone`)
232
- ```typescript
233
- import { GeoFlag, GeoPhone } from '@dxtmisha/functional-basic';
234
-
235
- // Flags
236
- const flagHelper = new GeoFlag();
237
- const flagIcon = flagHelper.getFlag('VN'); // Vietnam flag emoji/svg code
238
-
239
- // Phones
240
- const phoneInfo = GeoPhone.getByPhone('+84900000000');
241
- console.log(phoneInfo.phone); // Cleaned phone string
242
- const mask = GeoPhone.toMask('84900000000'); // Returns formatted phone mask
95
+ // Flags & Phones
96
+ const flag = new GeoFlag().getFlag('VN');
97
+ const phoneInfo = GeoPhone.getByPhone('+84900000000'); // .phone = cleaned string
98
+ const mask = GeoPhone.toMask('84900000000');
243
99
  ```
244
100
 
245
- ---
246
-
247
- ### 4. DOM and Safe Event Management (`EventItem`)
248
-
249
- `EventItem` provides memory-leak proof DOM event management by automating listener binding and unbinding.
250
-
101
+ ### 4. DOM, Safe Events & Helpers
251
102
  ```typescript
252
- import { EventItem } from '@dxtmisha/functional-basic';
253
-
254
- // Initialize the event listener (attached to element selector or Window)
255
- const clickListener = new EventItem(
256
- window,
257
- 'click',
258
- (event) => {
259
- console.log('Window clicked', event);
260
- },
261
- { passive: true }
262
- );
103
+ import { EventItem, goScrollSmooth, writeClipboardData, getClipboardData } from '@dxtmisha/functional-basic';
263
104
 
264
- // Start listening
105
+ // Leak-proof Event management
106
+ const clickListener = new EventItem(window, 'click', (e) => console.log(e), { passive: true });
265
107
  clickListener.start();
108
+ clickListener.stop(); // Call on destroy/cleanup!
266
109
 
267
- // Stop listening (always call when cleaning up/destroying component contexts!)
268
- clickListener.stop();
269
- ```
270
-
271
- #### Scrolling & Clipboard Helpers
272
- ```typescript
273
- import { goScrollSmooth, writeClipboardData, getClipboardData } from '@dxtmisha/functional-basic';
274
-
275
- // Scroll element into view smoothly
110
+ // DOM / Clipboard
276
111
  goScrollSmooth(document.getElementById('target'));
277
-
278
- // Copy text to clipboard
279
- await writeClipboardData('Text to copy');
280
-
281
- // Read from clipboard
112
+ await writeClipboardData('text');
282
113
  const text = await getClipboardData();
283
114
  ```
284
115
 
285
- ---
286
-
287
116
  ### 5. Search & Formatting Utilities
288
-
289
- #### `SearchList`
290
- A highly-optimized client-side text searching class featuring search highlights.
291
- ```typescript
292
- import { SearchList } from '@dxtmisha/functional-basic';
293
-
294
- const users = [
295
- { name: 'John Doe', email: 'john@example.com' },
296
- { name: 'Jane Smith', email: 'jane@example.com' },
297
- ];
298
-
299
- // Instantiation: items, fields to search in, current search query, search options
300
- const searcher = new SearchList(users, ['name', 'email'], 'john');
301
-
302
- // Execute and retrieve filtered results with highlight match markup
303
- const results = searcher.to();
304
- // returns: Array of results with exact matching highlights in matching keys
305
- ```
306
-
307
- #### `Formatters`
308
- Automates schema-based transformations of structured lists or objects.
309
117
  ```typescript
310
- import { Formatters, FormattersType } from '@dxtmisha/functional-basic';
118
+ import { SearchList, Formatters, FormattersType } from '@dxtmisha/functional-basic';
311
119
 
312
- const rawData = { price: 12000, date: '2026-06-18' };
120
+ // Search List with highlights
121
+ const searcher = new SearchList([{ name: 'John Doe' }], ['name'], 'john');
122
+ const results = searcher.to(); // returns matching items with highlighted markup in matching keys
313
123
 
124
+ // Object Formatter
314
125
  const formatter = new Formatters({
315
126
  price: { type: FormattersType.currency, options: 'USD' },
316
127
  date: { type: FormattersType.date, options: { month: 'long', year: 'numeric' } }
317
- }, rawData);
318
-
319
- const formatted = formatter.to();
320
- // { price: '$12,000.00', date: 'June 2026' }
128
+ }, { price: 12000, date: '2026-06-18' });
129
+ const formatted = formatter.to(); // { price: '$12,000.00', date: 'June 2026' }
321
130
  ```
322
131
 
323
- ---
324
-
325
- ### 6. General Utility Functions
326
-
327
- Core lightweight utilities:
328
- - `isFilled(value)`: Checks if string, array, object, boolean or number has filled content. Returns `false` for `[]`, `{}`, `''`, `null`, `undefined`.
329
- - `isDomRuntime()`: Safe isomorphic environment check. Returns `true` if code is running in a browser runtime.
330
- - `copyObject(value)`: Performs a quick, deep object clone.
331
- - `anyToString(value)`: Converts any type to its clean string representation.
332
- - `sleep(ms)`: Promisified setTimeout wrapper for async delay.
333
-
132
+ ### 6. General Helpers
334
133
  ```typescript
335
- import { isFilled, isDomRuntime, copyObject, sleep } from '@dxtmisha/functional-basic';
336
-
337
- if (isDomRuntime()) {
338
- console.log('Running in browser');
339
- }
340
-
341
- if (isFilled(myArray)) {
342
- const cloned = copyObject(myArray);
343
- }
134
+ import { isFilled, isDomRuntime, copyObject, anyToString, sleep } from '@dxtmisha/functional-basic';
344
135
 
136
+ isFilled([]); // false (works for strings, arrays, objects, numbers, booleans)
137
+ isDomRuntime(); // true if in browser
138
+ const cloned = copyObject({ a: 1 });
139
+ const str = anyToString(123);
345
140
  await sleep(500);
346
141
  ```
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dxtmisha/functional-basic",
3
3
  "private": false,
4
- "version": "1.6.2",
4
+ "version": "1.6.4",
5
5
  "type": "module",
6
6
  "description": "Foundational utility library for modern web development — HTTP client, geolocation, i18n, SEO meta tags, caching, storage, DOM utilities, and more. Framework-agnostic, zero dependencies, TypeScript-first.",
7
7
  "keywords": [