@ylsoo/core 1.1.0 → 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/README.md CHANGED
@@ -1,17 +1,18 @@
1
1
  <div align="center">
2
- <h1>@ylsoo/core</h1>
3
- <p><b>The official, zero-dependency SDK powering all premium Ylsoo products.</b></p>
2
+ <h1>@ylsoo/core (v2.0 Enterprise)</h1>
3
+ <p><b>The official, enterprise-grade SDK powering advanced Ylsoo web and server products.</b></p>
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@ylsoo/core.svg?style=flat-square)](https://www.npmjs.com/package/@ylsoo/core)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
7
7
  [![TypeScript Ready](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)](https://www.typescriptlang.org/)
8
+ [![Cross-Platform](https://img.shields.io/badge/Cross--Platform-Node.js%20%7C%20Browser-brightgreen?style=flat-square)](#)
8
9
  </div>
9
10
 
10
11
  <hr>
11
12
 
12
13
  ## 🚀 Overview
13
14
 
14
- `@ylsoo/core` provides fundamental, blazing-fast utility functions designed specifically for integrating Ylsoo services. Built completely from the ground up without any third-party dependencies, it guarantees ultra-fast execution and zero bloat.
15
+ `@ylsoo/core` v2 has been completely rewritten into a powerful, modular architecture. It provides blazing-fast utility functions designed specifically for Ylsoo services. It runs identically on **modern browsers** and **Node.js** servers thanks to custom polyfills acting entirely natively, without a single external dependency!
15
16
 
16
17
  ## 📦 Installation
17
18
 
@@ -19,89 +20,73 @@
19
20
  npm i @ylsoo/core
20
21
  ```
21
22
 
22
- *Note: Fully typed out-of-the-box for perfect IDE intellisense!*
23
-
24
23
  ## 🛠️ API Reference
25
24
 
26
- ### 1. Ylsoo Console (`logger`)
27
- A beautifully formatted console utility utilizing native ANSI escape codes for local development.
28
-
25
+ ### 1. 🔐 Distributed Security (`ylsoo.crypto`)
26
+ Leverages Web Crypto API natively to perform secure operations identically across browsers and servers.
29
27
  ```javascript
30
28
  const ylsoo = require('@ylsoo/core');
31
29
 
32
- ylsoo.logger.info('System initializing...');
33
- ylsoo.logger.success('Database connected successfully!');
34
- ylsoo.logger.warn('Rate limit approaching.');
35
- ylsoo.logger.error('Critical failure detected.');
36
- ```
30
+ // 1. Generate Secure V4 UUIDs
31
+ const sessionID = ylsoo.crypto.uuid();
37
32
 
38
- ### 2. Ylsoo Request Engine (`http`)
39
- A robust wrapper around the native `fetch` API. It automatically handles stringifying bodies, applying correct headers, parsing JSON, and safely throwing formatted errors.
33
+ // 2. Hash strings natively
34
+ const secretHash = await ylsoo.crypto.hash('my_super_secret');
35
+
36
+ // 3. Encode/Decode Base64
37
+ const encoded = ylsoo.crypto.encodeBase64('user:pass');
38
+ ```
40
39
 
40
+ ### 2. ⚡ Event Bus (`ylsoo.events`)
41
+ An enterprise Publisher/Subscriber mechanism to handle inter-component state within Ylsoo frontends or microservices.
41
42
  ```javascript
42
- const ylsoo = require('@ylsoo/core');
43
+ // Component A (Subscribes)
44
+ const unsubscribe = ylsoo.events.on('user:login', (user) => {
45
+ console.log('Welcome back,', user.name);
46
+ });
47
+
48
+ // Component B (Publishes)
49
+ ylsoo.events.emit('user:login', { name: 'Admin' });
43
50
 
51
+ // Listen exactly once
52
+ ylsoo.events.once('system:boot', bootFunction);
53
+ ```
54
+
55
+ ### 3. 🌐 Ylsoo Request Engine (`ylsoo.http`)
56
+ A robust wrapper around the versatile `fetch` API. It handles JSON stringification, applies custom headers, parses JSON, and safely formats errors automatically.
57
+ ```javascript
44
58
  async function fetchUserData() {
45
59
  try {
46
60
  const data = await ylsoo.http.get('https://api.ylsoo.com/v1/user/me');
47
- console.log(data);
48
61
  } catch (error) {
49
62
  ylsoo.logger.error('Failed to fetch user', error);
50
63
  }
51
64
  }
52
65
  ```
53
66
 
54
- ### 3. Ylsoo Memory Cache (`cache`)
55
- A fast, volatile in-memory key/value store with Time-To-Live (TTL) functionality.
56
-
67
+ ### 4. 🧠 Ylsoo Memory Cache (`ylsoo.cache`)
68
+ A volatile in-memory Map structure featuring native Time-To-Live (TTL) functionality.
57
69
  ```javascript
58
- const ylsoo = require('@ylsoo/core');
59
-
60
- // Cache a complex object for 5 seconds (5000 ms)
61
- ylsoo.cache.set('session_token', { id: 123 }, 5000);
62
-
63
- // Retrieve it instantly
64
- const session = ylsoo.cache.get('session_token');
65
-
66
- // Will return null after 5 seconds
67
- setTimeout(() => {
68
- console.log(ylsoo.cache.get('session_token')); // null
69
- }, 5100);
70
- ```
71
-
72
- ### 4. Advanced Core Utilities
73
-
74
- #### `sleep(ms)`
75
- Promise-based execution halter.
76
- ```javascript
77
- await ylsoo.sleep(2000); // Waits 2 seconds
70
+ // Cache an object for 5000 ms (5 seconds)
71
+ ylsoo.cache.set('session', { id: 123 }, 5000);
72
+ const session = ylsoo.cache.get('session');
78
73
  ```
79
74
 
80
- #### `deepClone(obj)`
81
- Safely fully clones an object without retaining references, utilizing modern native standards where available.
75
+ ### 5. 🖥️ Ylsoo Console (`ylsoo.logger`)
76
+ Formatted console utility employing native ANSI escape codes specifically designed for local backends.
82
77
  ```javascript
83
- const copy = ylsoo.deepClone(complexObject);
84
- ```
85
-
86
- #### `debounce(func, wait)`
87
- Throttles function execution to ensure high performance during spam events (like window resizing or typing).
88
- ```javascript
89
- const search = ylsoo.debounce(() => console.log('Searching...'), 300);
90
- ```
91
-
92
- #### `isEmpty(value)`
93
- Intelligently determines if strings, arrays, objects, maps, or sets are empty.
94
- ```javascript
95
- ylsoo.isEmpty({}); // true
96
- ylsoo.isEmpty([]); // true
97
- ylsoo.isEmpty("hello"); // false
78
+ ylsoo.logger.info('System initializing...');
79
+ ylsoo.logger.success('Database connected successfully!');
80
+ ylsoo.logger.warn('Rate limit approaching.');
81
+ ylsoo.logger.error('Critical failure detected.');
98
82
  ```
99
83
 
100
- #### `capitalize(str)`
101
- Easily standardize text formatting.
102
- ```javascript
103
- ylsoo.capitalize('ylsoo'); // 'Ylsoo'
104
- ```
84
+ ### 6. 🧰 Native Enterprise Utilies
85
+ - **`ylsoo.sleep(ms)`**: Promise-based execution halter.
86
+ - **`ylsoo.deepClone(obj)`**: Safely deep clones utilizing native modern standards like `structuredClone` when available.
87
+ - **`ylsoo.debounce(func, wait)`**: High performance throttling mechanics.
88
+ - **`ylsoo.isEmpty(val)`**: Semantic entity verification (detects empty Sets, Maps, Objects, Strings, Arrays).
89
+ - **`ylsoo.capitalize(str)`**: Automatic string standardizer.
105
90
 
106
91
  ---
107
92
  <div align="center">
package/index.d.ts CHANGED
@@ -1,42 +1,23 @@
1
1
  /**
2
- * @ylsoo/core Type Definitions
2
+ * @ylsoo/core v2.0.0 Type Definitions
3
+ * Cross-platform Enterprise SDK
3
4
  */
4
5
 
5
6
  declare module '@ylsoo/core' {
6
7
 
8
+ // --- Core Modules ---
9
+
7
10
  export class YlsooLogger {
8
- /** Logs an informational message */
9
11
  info(message: string | any): void;
10
- /** Logs a success message */
11
12
  success(message: string | any): void;
12
- /** Logs a warning message */
13
13
  warn(message: string | any): void;
14
- /** Logs an error message */
15
14
  error(message: string | any): void;
16
15
  }
17
16
 
18
17
  export class YlsooCache {
19
- /**
20
- * Set a key-value pair in memory
21
- * @param key String identifier
22
- * @param value The raw value to store
23
- * @param ttlMs Time to live in milliseconds (0 for infinite)
24
- */
25
18
  set(key: string, value: any, ttlMs?: number): void;
26
-
27
- /**
28
- * Retrieve a value from the cache. Returns null if expired or missing.
29
- */
30
19
  get<T = any>(key: string): T | null;
31
-
32
- /**
33
- * Delete a specific key from the cache
34
- */
35
20
  delete(key: string): boolean;
36
-
37
- /**
38
- * Clear all cached data
39
- */
40
21
  clear(): void;
41
22
  }
42
23
 
@@ -48,41 +29,63 @@ declare module '@ylsoo/core' {
48
29
  }
49
30
 
50
31
  export class YlsooHttp {
51
- /** Makes a raw fetch request but automatically handles JSON mapping and errors */
52
32
  request<T = any>(endpoint: string, options?: YlsooHttpOptions): Promise<T>;
53
-
54
- /** Performs a GET request */
55
33
  get<T = any>(endpoint: string, headers?: Record<string, string>): Promise<T>;
56
-
57
- /** Performs a POST request with an automatic JSON-stringified body */
58
34
  post<T = any>(endpoint: string, body: any, headers?: Record<string, string>): Promise<T>;
59
35
  }
60
36
 
37
+ // --- Security Modules ---
38
+
39
+ export class YlsooCrypto {
40
+ /** Base64 encodes a utf-8 string securely */
41
+ encodeBase64(str: string): string;
42
+
43
+ /** Base64 decodes a string */
44
+ decodeBase64(base64: string): string;
45
+
46
+ /** Natively generates a secure SHA-256 hash */
47
+ hash(str: string): Promise<string>;
48
+
49
+ /** Generates a cryptographically strong v4 UUID */
50
+ uuid(): string;
51
+ }
52
+
53
+ // --- Event Modules ---
54
+
55
+ export class YlsooEventBus {
56
+ /** Subscribe to an event. Returns an unsubscribe function. */
57
+ on(event: string, callback: (data?: any) => void): () => void;
58
+
59
+ /** Unsubscribe from an event. */
60
+ off(event: string, callback: (data?: any) => void): void;
61
+
62
+ /** Publish an event to all subscribers. */
63
+ emit(event: string, data?: any): void;
64
+
65
+ /** Subscribe to an event, un-subscribing immediately after first emission. */
66
+ once(event: string, callback: (data?: any) => void): void;
67
+
68
+ /** clear all event listeners */
69
+ clear(): void;
70
+ }
71
+
72
+ // --- Main Export ---
73
+
61
74
  export class YlsooCore {
62
75
  version: string;
63
76
 
64
- /** The official Ylsoo logging console */
77
+ // Systems
65
78
  logger: YlsooLogger;
66
-
67
- /** The official Ylsoo memory cache */
68
79
  cache: YlsooCache;
69
-
70
- /** The official Ylsoo request engine */
71
80
  http: YlsooHttp;
81
+ crypto: YlsooCrypto;
82
+ events: YlsooEventBus;
72
83
 
73
- /** Halt execution for a set duration */
84
+ // Utilities
74
85
  sleep(ms: number): Promise<void>;
75
-
76
- /** Safely deep clone an object */
77
86
  deepClone<T>(obj: T): T;
78
-
79
- /** Creates a debounced version of a function */
80
87
  debounce<T extends (...args: any[]) => any>(func: T, wait: number): (...args: Parameters<T>) => void;
81
-
82
- /** Check if an array, string, object, map, or set is semantically empty */
83
88
  isEmpty(value: any): boolean;
84
-
85
- /** Capitalizes the first letter of a string */
86
89
  capitalize(str: string): string;
87
90
  }
88
91
 
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@ylsoo/core",
3
- "version": "1.1.0",
4
- "description": "Core utility functions for Ylsoo projects",
5
- "main": "index.js",
3
+ "version": "2.0.0",
4
+ "description": "Enterprise cross-platform SDK for Ylsoo projects",
5
+ "main": "src/index.js",
6
6
  "types": "index.d.ts",
7
7
  "files": [
8
- "index.js",
8
+ "src/",
9
9
  "index.d.ts",
10
10
  "README.md"
11
11
  ],
@@ -15,11 +15,14 @@
15
15
  "keywords": [
16
16
  "ylsoo",
17
17
  "core",
18
- "utilities",
18
+ "enterprise",
19
19
  "sdk",
20
20
  "fetch",
21
21
  "logger",
22
- "cache"
22
+ "cache",
23
+ "crypto",
24
+ "uuid",
25
+ "events"
23
26
  ],
24
27
  "author": "Ylsoo",
25
28
  "license": "MIT",
@@ -0,0 +1,31 @@
1
+ class YlsooCache {
2
+ constructor() {
3
+ this.store = new Map();
4
+ }
5
+
6
+ set(key, value, ttlMs = 0) {
7
+ const expiresAt = ttlMs > 0 ? Date.now() + ttlMs : null;
8
+ this.store.set(key, { value, expiresAt });
9
+ }
10
+
11
+ get(key) {
12
+ const item = this.store.get(key);
13
+ if (!item) return null;
14
+
15
+ if (item.expiresAt && Date.now() > item.expiresAt) {
16
+ this.store.delete(key);
17
+ return null;
18
+ }
19
+ return item.value;
20
+ }
21
+
22
+ delete(key) {
23
+ return this.store.delete(key);
24
+ }
25
+
26
+ clear() {
27
+ this.store.clear();
28
+ }
29
+ }
30
+
31
+ module.exports = { YlsooCache };
@@ -0,0 +1,39 @@
1
+ class YlsooLogger {
2
+ constructor() {
3
+ this.colors = {
4
+ reset: "\x1b[0m",
5
+ info: "\x1b[36m", // Cyan
6
+ success: "\x1b[32m", // Green
7
+ warn: "\x1b[33m", // Yellow
8
+ error: "\x1b[31m", // Red
9
+ ylsoo: "\x1b[35m" // Magenta
10
+ };
11
+ }
12
+
13
+ _format(level, message, color) {
14
+ // Only use colors in Node.js, not browsers. Check process briefly.
15
+ const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
16
+ if (isNode) {
17
+ return `${this.colors.ylsoo}[Ylsoo]${this.colors.reset} ${color}[${level.toUpperCase()}]${this.colors.reset} ${message}`;
18
+ }
19
+ return `[Ylsoo] [${level.toUpperCase()}] ${message}`;
20
+ }
21
+
22
+ info(message) {
23
+ console.log(this._format('info', message, this.colors.info));
24
+ }
25
+
26
+ success(message) {
27
+ console.log(this._format('success', message, this.colors.success));
28
+ }
29
+
30
+ warn(message) {
31
+ console.warn(this._format('warn', message, this.colors.warn));
32
+ }
33
+
34
+ error(message) {
35
+ console.error(this._format('error', message, this.colors.error));
36
+ }
37
+ }
38
+
39
+ module.exports = { YlsooLogger };
@@ -0,0 +1,69 @@
1
+ class YlsooEventBus {
2
+ constructor() {
3
+ this.events = {};
4
+ }
5
+
6
+ /**
7
+ * Subscribe to an event
8
+ * @param {string} event
9
+ * @param {Function} callback
10
+ * @returns {Function} Unsubscribe function
11
+ */
12
+ on(event, callback) {
13
+ if (!this.events[event]) {
14
+ this.events[event] = [];
15
+ }
16
+ this.events[event].push(callback);
17
+
18
+ // Return an un-subscriber
19
+ return () => this.off(event, callback);
20
+ }
21
+
22
+ /**
23
+ * Unsubscribe from an event
24
+ * @param {string} event
25
+ * @param {Function} callback
26
+ */
27
+ off(event, callback) {
28
+ if (!this.events[event]) return;
29
+ this.events[event] = this.events[event].filter(cb => cb !== callback);
30
+ }
31
+
32
+ /**
33
+ * Publish an event with optional payload
34
+ * @param {string} event
35
+ * @param {*} data
36
+ */
37
+ emit(event, data) {
38
+ if (!this.events[event]) return;
39
+ this.events[event].forEach(callback => {
40
+ try {
41
+ callback(data);
42
+ } catch (err) {
43
+ console.error(`[Ylsoo Event Bus] Error in callback for event "${event}":`, err);
44
+ }
45
+ });
46
+ }
47
+
48
+ /**
49
+ * Listen for an event exactly once
50
+ * @param {string} event
51
+ * @param {Function} callback
52
+ */
53
+ once(event, callback) {
54
+ const wrapper = (data) => {
55
+ this.off(event, wrapper);
56
+ callback(data);
57
+ };
58
+ this.on(event, wrapper);
59
+ }
60
+
61
+ /**
62
+ * Clear all events
63
+ */
64
+ clear() {
65
+ this.events = {};
66
+ }
67
+ }
68
+
69
+ module.exports = { YlsooEventBus };
@@ -0,0 +1,49 @@
1
+ class YlsooHttp {
2
+ async request(endpoint, options = {}) {
3
+ const defaultHeaders = {
4
+ 'Content-Type': 'application/json',
5
+ 'User-Agent': 'Ylsoo-Core/2.0'
6
+ };
7
+
8
+ const config = {
9
+ ...options,
10
+ headers: {
11
+ ...defaultHeaders,
12
+ ...options.headers
13
+ }
14
+ };
15
+
16
+ if (config.body && typeof config.body === 'object') {
17
+ config.body = JSON.stringify(config.body);
18
+ }
19
+
20
+ try {
21
+ const response = await fetch(endpoint, config);
22
+ const isJson = response.headers.get('content-type')?.includes('application/json');
23
+
24
+ const data = isJson ? await response.json() : await response.text();
25
+
26
+ if (!response.ok) {
27
+ throw {
28
+ status: response.status,
29
+ message: response.statusText,
30
+ data
31
+ };
32
+ }
33
+
34
+ return data;
35
+ } catch (error) {
36
+ throw new Error(`[Ylsoo HTTP Error]: ${error.message || JSON.stringify(error)}`);
37
+ }
38
+ }
39
+
40
+ get(endpoint, headers = {}) {
41
+ return this.request(endpoint, { method: 'GET', headers });
42
+ }
43
+
44
+ post(endpoint, body, headers = {}) {
45
+ return this.request(endpoint, { method: 'POST', body, headers });
46
+ }
47
+ }
48
+
49
+ module.exports = { YlsooHttp };
package/src/index.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @ylsoo/core v2.0.0
3
+ * Enterprise utilities for both Node.js and the Web.
4
+ */
5
+
6
+ const { YlsooHttp } = require('./http/client');
7
+ const { YlsooLogger } = require('./core/logger');
8
+ const { YlsooCache } = require('./core/cache');
9
+ const { YlsooCrypto } = require('./security/crypto');
10
+ const { YlsooEventBus } = require('./events/bus');
11
+ const { YlsooHelpers } = require('./utils/helpers');
12
+
13
+ class YlsooCore {
14
+ constructor() {
15
+ this.version = '2.0.0';
16
+
17
+ // Core Modules
18
+ this.http = new YlsooHttp();
19
+ this.logger = new YlsooLogger();
20
+ this.cache = new YlsooCache();
21
+
22
+ // Advanced Modules
23
+ this.crypto = new YlsooCrypto();
24
+ this.events = new YlsooEventBus();
25
+ this.helpers = new YlsooHelpers();
26
+ }
27
+
28
+ // --- Helper Proxies to keep backwards compatibility with v1.1.0 ---
29
+ sleep(ms) { return this.helpers.sleep(ms); }
30
+ deepClone(obj) { return this.helpers.deepClone(obj); }
31
+ debounce(func, wait) { return this.helpers.debounce(func, wait); }
32
+ isEmpty(val) { return this.helpers.isEmpty(val); }
33
+ capitalize(str) { return this.helpers.capitalize(str); }
34
+ }
35
+
36
+ module.exports = new YlsooCore();
@@ -0,0 +1,67 @@
1
+ class YlsooCrypto {
2
+ /**
3
+ * Base64 encode a string
4
+ * @param {string} str
5
+ * @returns {string}
6
+ */
7
+ encodeBase64(str) {
8
+ if (typeof globalThis.btoa === 'function') {
9
+ return globalThis.btoa(str);
10
+ }
11
+ return Buffer.from(str).toString('base64');
12
+ }
13
+
14
+ /**
15
+ * Base64 decode a string
16
+ * @param {string} base64
17
+ * @returns {string}
18
+ */
19
+ decodeBase64(base64) {
20
+ if (typeof globalThis.atob === 'function') {
21
+ return globalThis.atob(base64);
22
+ }
23
+ return Buffer.from(base64, 'base64').toString('utf-8');
24
+ }
25
+
26
+ /**
27
+ * Creates a SHA-256 hash of a string natively
28
+ * @param {string} str
29
+ * @returns {Promise<string>}
30
+ */
31
+ async hash(str) {
32
+ // Attempt standard Web Crypto API (Browser + Modern Node)
33
+ if (globalThis.crypto && globalThis.crypto.subtle) {
34
+ const msgBuffer = new TextEncoder().encode(str);
35
+ const hashBuffer = await globalThis.crypto.subtle.digest('SHA-256', msgBuffer);
36
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
37
+ return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
38
+ }
39
+
40
+ // Fallback for older Node.js contexts
41
+ try {
42
+ const crypto = require('crypto');
43
+ return crypto.createHash('sha256').update(str).digest('hex');
44
+ } catch(err) {
45
+ throw new Error('[Ylsoo Crypto Error] No secure hashing engine available on this platform.');
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Generate a secure random v4 UUID
51
+ * @returns {string}
52
+ */
53
+ uuid() {
54
+ if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {
55
+ return globalThis.crypto.randomUUID();
56
+ }
57
+
58
+ // Fallback UUID v4 generator
59
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
60
+ const r = Math.random() * 16 | 0;
61
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
62
+ return v.toString(16);
63
+ });
64
+ }
65
+ }
66
+
67
+ module.exports = { YlsooCrypto };
@@ -0,0 +1,43 @@
1
+ class YlsooHelpers {
2
+ sleep(ms) {
3
+ return new Promise(resolve => setTimeout(resolve, ms));
4
+ }
5
+
6
+ deepClone(obj) {
7
+ if (typeof structuredClone === 'function') {
8
+ return structuredClone(obj);
9
+ }
10
+ return JSON.parse(JSON.stringify(obj));
11
+ }
12
+
13
+ debounce(func, wait) {
14
+ let timeout;
15
+ return function executedFunction(...args) {
16
+ const later = () => {
17
+ clearTimeout(timeout);
18
+ func(...args);
19
+ };
20
+ clearTimeout(timeout);
21
+ timeout = setTimeout(later, wait);
22
+ };
23
+ }
24
+
25
+ isEmpty(value) {
26
+ if (value === null || value === undefined) return true;
27
+ if (typeof value === 'string' || Array.isArray(value)) return value.length === 0;
28
+ if (typeof value === 'object') {
29
+ if (value instanceof Map || value instanceof Set) return value.size === 0;
30
+ return Object.keys(value).length === 0;
31
+ }
32
+ return false;
33
+ }
34
+
35
+ capitalize(str) {
36
+ if (typeof str !== 'string' || str.length === 0) {
37
+ return str;
38
+ }
39
+ return str.charAt(0).toUpperCase() + str.slice(1);
40
+ }
41
+ }
42
+
43
+ module.exports = { YlsooHelpers };
package/index.js DELETED
@@ -1,202 +0,0 @@
1
- /**
2
- * @ylsoo/core
3
- * Premium utility functions for Ylsoo projects
4
- * Zero dependency, extremely fast, robust.
5
- */
6
-
7
- class YlsooLogger {
8
- constructor() {
9
- this.colors = {
10
- reset: "\x1b[0m",
11
- info: "\x1b[36m", // Cyan
12
- success: "\x1b[32m", // Green
13
- warn: "\x1b[33m", // Yellow
14
- error: "\x1b[31m", // Red
15
- ylsoo: "\x1b[35m" // Magenta
16
- };
17
- }
18
-
19
- _format(level, message, color) {
20
- const time = new Date().toISOString().split('T')[1].slice(0, -1);
21
- return `${this.colors.ylsoo}[Ylsoo]${this.colors.reset} ${color}[${level.toUpperCase()}]${this.colors.reset} ${message}`;
22
- }
23
-
24
- info(message) {
25
- console.log(this._format('info', message, this.colors.info));
26
- }
27
-
28
- success(message) {
29
- console.log(this._format('success', message, this.colors.success));
30
- }
31
-
32
- warn(message) {
33
- console.warn(this._format('warn', message, this.colors.warn));
34
- }
35
-
36
- error(message) {
37
- console.error(this._format('error', message, this.colors.error));
38
- }
39
- }
40
-
41
- class YlsooCache {
42
- constructor() {
43
- this.store = new Map();
44
- }
45
-
46
- /**
47
- * Set a key-value pair with an optional Time-To-Live
48
- * @param {string} key
49
- * @param {*} value
50
- * @param {number} ttlMs - Time to live in milliseconds
51
- */
52
- set(key, value, ttlMs = 0) {
53
- const expiresAt = ttlMs > 0 ? Date.now() + ttlMs : null;
54
- this.store.set(key, { value, expiresAt });
55
- }
56
-
57
- get(key) {
58
- const item = this.store.get(key);
59
- if (!item) return null;
60
-
61
- if (item.expiresAt && Date.now() > item.expiresAt) {
62
- this.store.delete(key);
63
- return null;
64
- }
65
- return item.value;
66
- }
67
-
68
- delete(key) {
69
- return this.store.delete(key);
70
- }
71
-
72
- clear() {
73
- this.store.clear();
74
- }
75
- }
76
-
77
- class YlsooHttp {
78
- /**
79
- * Premium wrapper for fetch
80
- * @param {string} endpoint
81
- * @param {object} options
82
- * @returns {Promise<any>}
83
- */
84
- async request(endpoint, options = {}) {
85
- const defaultHeaders = {
86
- 'Content-Type': 'application/json',
87
- 'User-Agent': 'Ylsoo-Core/1.1'
88
- };
89
-
90
- const config = {
91
- ...options,
92
- headers: {
93
- ...defaultHeaders,
94
- ...options.headers
95
- }
96
- };
97
-
98
- if (config.body && typeof config.body === 'object') {
99
- config.body = JSON.stringify(config.body);
100
- }
101
-
102
- try {
103
- const response = await fetch(endpoint, config);
104
- const isJson = response.headers.get('content-type')?.includes('application/json');
105
-
106
- const data = isJson ? await response.json() : await response.text();
107
-
108
- if (!response.ok) {
109
- throw {
110
- status: response.status,
111
- message: response.statusText,
112
- data
113
- };
114
- }
115
-
116
- return data;
117
- } catch (error) {
118
- throw new Error(`[Ylsoo HTTP Error]: ${error.message || JSON.stringify(error)}`);
119
- }
120
- }
121
-
122
- get(endpoint, headers = {}) {
123
- return this.request(endpoint, { method: 'GET', headers });
124
- }
125
-
126
- post(endpoint, body, headers = {}) {
127
- return this.request(endpoint, { method: 'POST', body, headers });
128
- }
129
- }
130
-
131
- class YlsooCore {
132
- constructor() {
133
- this.version = '1.1.0';
134
- this.logger = new YlsooLogger();
135
- this.cache = new YlsooCache();
136
- this.http = new YlsooHttp();
137
- }
138
-
139
- /**
140
- * Sleep for a given amount of time (Promise based)
141
- * @param {number} ms
142
- */
143
- sleep(ms) {
144
- return new Promise(resolve => setTimeout(resolve, ms));
145
- }
146
-
147
- /**
148
- * Deep clone an object natively
149
- * @param {object} obj
150
- */
151
- deepClone(obj) {
152
- if (typeof structuredClone === 'function') {
153
- return structuredClone(obj);
154
- }
155
- return JSON.parse(JSON.stringify(obj));
156
- }
157
-
158
- /**
159
- * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed
160
- * @param {Function} func
161
- * @param {number} wait
162
- */
163
- debounce(func, wait) {
164
- let timeout;
165
- return function executedFunction(...args) {
166
- const later = () => {
167
- clearTimeout(timeout);
168
- func(...args);
169
- };
170
- clearTimeout(timeout);
171
- timeout = setTimeout(later, wait);
172
- };
173
- }
174
-
175
- /**
176
- * Simple utility to verify if a value is semantically empty
177
- * @param {*} value
178
- */
179
- isEmpty(value) {
180
- if (value === null || value === undefined) return true;
181
- if (typeof value === 'string' || Array.isArray(value)) return value.length === 0;
182
- if (typeof value === 'object') {
183
- if (value instanceof Map || value instanceof Set) return value.size === 0;
184
- return Object.keys(value).length === 0;
185
- }
186
- return false;
187
- }
188
-
189
- /**
190
- * Simple utility to capitalize a string
191
- * @param {string} str - The string to capitalize
192
- * @returns {string} Capitalized string
193
- */
194
- capitalize(str) {
195
- if (typeof str !== 'string' || str.length === 0) {
196
- return str;
197
- }
198
- return str.charAt(0).toUpperCase() + str.slice(1);
199
- }
200
- }
201
-
202
- module.exports = new YlsooCore();