@onurege3467/zerohelper 10.3.0 → 11.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.
Files changed (81) hide show
  1. package/README.md +9 -779
  2. package/dist/index.js +19 -44
  3. package/package.json +21 -70
  4. package/dist/bin/commands/cache.d.ts +0 -2
  5. package/dist/bin/commands/cache.js +0 -92
  6. package/dist/bin/commands/db-backup.d.ts +0 -3
  7. package/dist/bin/commands/db-backup.js +0 -118
  8. package/dist/bin/commands/db.d.ts +0 -2
  9. package/dist/bin/commands/db.js +0 -334
  10. package/dist/bin/commands/import-export.d.ts +0 -3
  11. package/dist/bin/commands/import-export.js +0 -123
  12. package/dist/bin/commands/init.d.ts +0 -2
  13. package/dist/bin/commands/init.js +0 -85
  14. package/dist/bin/commands/migrate.d.ts +0 -3
  15. package/dist/bin/commands/migrate.js +0 -167
  16. package/dist/bin/commands/repl.d.ts +0 -2
  17. package/dist/bin/commands/repl.js +0 -96
  18. package/dist/bin/commands/seed.d.ts +0 -2
  19. package/dist/bin/commands/seed.js +0 -76
  20. package/dist/bin/commands/zpack.d.ts +0 -2
  21. package/dist/bin/commands/zpack.js +0 -36
  22. package/dist/bin/index.d.ts +0 -2
  23. package/dist/bin/index.js +0 -28
  24. package/dist/bin/types.d.ts +0 -22
  25. package/dist/bin/types.js +0 -2
  26. package/dist/bin/utils/config.d.ts +0 -3
  27. package/dist/bin/utils/config.js +0 -78
  28. package/dist/bin/utils/prompts.d.ts +0 -3
  29. package/dist/bin/utils/prompts.js +0 -115
  30. package/dist/bin/zero.d.ts +0 -2
  31. package/dist/bin/zero.js +0 -849
  32. package/dist/database/IDatabase.d.ts +0 -71
  33. package/dist/database/IDatabase.js +0 -48
  34. package/dist/database/cacheWrapper.d.ts +0 -34
  35. package/dist/database/cacheWrapper.js +0 -214
  36. package/dist/database/index.d.ts +0 -12
  37. package/dist/database/index.js +0 -100
  38. package/dist/database/json.d.ts +0 -32
  39. package/dist/database/json.js +0 -208
  40. package/dist/database/migration.d.ts +0 -21
  41. package/dist/database/migration.js +0 -97
  42. package/dist/database/mongodb.d.ts +0 -26
  43. package/dist/database/mongodb.js +0 -145
  44. package/dist/database/mysql.d.ts +0 -29
  45. package/dist/database/mysql.js +0 -282
  46. package/dist/database/pg.d.ts +0 -28
  47. package/dist/database/pg.js +0 -200
  48. package/dist/database/redis.d.ts +0 -31
  49. package/dist/database/redis.js +0 -176
  50. package/dist/database/seeder.d.ts +0 -20
  51. package/dist/database/seeder.js +0 -37
  52. package/dist/database/sqlite.d.ts +0 -26
  53. package/dist/database/sqlite.js +0 -211
  54. package/dist/database/telemetry.d.ts +0 -35
  55. package/dist/database/telemetry.js +0 -41
  56. package/dist/database/toon.d.ts +0 -33
  57. package/dist/database/toon.js +0 -244
  58. package/dist/database/types.d.ts +0 -71
  59. package/dist/database/types.js +0 -2
  60. package/dist/database/zpack.d.ts +0 -75
  61. package/dist/database/zpack.js +0 -616
  62. package/dist/functions/ai.d.ts +0 -126
  63. package/dist/functions/ai.js +0 -387
  64. package/dist/functions/index.d.ts +0 -223
  65. package/dist/functions/index.js +0 -686
  66. package/dist/functions/security.d.ts +0 -15
  67. package/dist/functions/security.js +0 -46
  68. package/dist/functions/toon.d.ts +0 -10
  69. package/dist/functions/toon.js +0 -214
  70. package/dist/functions/worker.d.ts +0 -5
  71. package/dist/functions/worker.js +0 -35
  72. package/dist/index.d.ts +0 -8
  73. package/dist/migrations/1767521950635_test_migration.d.ts +0 -3
  74. package/dist/migrations/1767521950635_test_migration.js +0 -11
  75. package/dist/migrations/1767522158826_create_users_table.d.ts +0 -2
  76. package/dist/migrations/1767522158826_create_users_table.js +0 -11
  77. package/dist/package.json +0 -79
  78. package/dist/tests/test.d.ts +0 -1
  79. package/dist/tests/test.js +0 -26
  80. package/dist/zero.config.d.ts +0 -10
  81. package/dist/zero.config.js +0 -13
package/README.md CHANGED
@@ -1,793 +1,23 @@
1
- # 🚀 ZeroHelper - The Ultimate Elite Node.js Utility & Database Framework
1
+ # @onurege3467/zerohelper
2
2
 
3
- [![Version](https://img.shields.io/npm/v/@onurege3467/zerohelper?style=for-the-badge)](https://www.npmjs.com/package/@onurege3467/zerohelper)
4
- [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=for-the-badge&logo=typescript)](https://www.typescriptlang.org/)
5
- [![License](https://img.shields.io/badge/License-ISC-green?style=for-the-badge)](https://opensource.org/licenses/ISC)
3
+ ZeroHelper - Meta package for backward compatibility.
6
4
 
7
- **ZeroHelper** is an elite-level, high-performance, and fully TypeScript-native utility ecosystem. Rebuilt from the ground up for version 10.2.6, it offers a unified abstraction layer over multiple database engines, advanced caching strategies, and a massive collection of "battle-tested" utility functions.
5
+ ## Description
8
6
 
9
- ---
7
+ This is a meta-package that re-exports all ZeroHelper modules for backward compatibility.
10
8
 
11
- ## 🏛️ Introduction & Philosophy
12
-
13
- ZeroHelper was born out of a simple need: **Stop reinventing the wheel in every project.**
14
-
15
- In modern backend development, we often find ourselves writing the same boilerplate for database connections, caching logic, slug generation, and password hashing. ZeroHelper consolidates these into a single, highly optimized dependency.
16
-
17
- ### 📜 The Origin Story & Commercial Heritage
18
- For the vast majority of its existence, **ZeroHelper operated as a strictly closed-source, proprietary framework.** It was the backbone of multiple high-revenue commercial platforms where failure was not an option. Every module, from the ZPack binary engine to the advanced caching layer, was engineered to meet the brutal demands of real-world commerce.
19
-
20
- Unlike many open-source libraries that start as experiments, ZeroHelper was forged in the fire of **private commercial ecosystems.** It served as a competitive advantage for years, providing enterprise-grade performance and stability to closed-door projects.
21
-
22
- We have now decided to open the vault. By open-sourcing this battle-hardened framework, we are giving the community access to a codebase that has already proven its worth in the most demanding commercial environments. When you use ZeroHelper, you aren't using an "alpha" project—you are using a framework that has been powering commercial success for years.
23
-
24
- ---
25
-
26
- ## 📑 Table of Contents
27
- 1. [Installation](#-installation)
28
- 2. [TypeScript Excellence](#-typescript-excellence)
29
- 3. [Database Unified API](#-database-unified-api)
30
- - [ZPack (High Performance Binary)](#zpack-binary)
31
- - [TOON (Native Object Notation DB)](#toon-db)
32
- - [SQL Adapters (MySQL, PostgreSQL, SQLite)](#sql-adapters)
33
- - [NoSQL Adapters (MongoDB, Redis)](#nosql-adapters)
34
- - [JSON Adapter](#json-adapter)
35
- 4. [Advanced Caching (Memory & Redis)](#-advanced-caching)
36
- 5. [Database Lifecycle Hooks](#-database-lifecycle-hooks)
37
- 6. [Telemetry & Performance Tracking](#-telemetry--performance-tracking)
38
- 7. [Database Migration System](#-database-migration-system)
39
- 8. [ZeroWorker (Worker Threads)](#-zeroworker-worker-threads)
40
- 9. [Zero-CLI Management Tool](#-zero-cli)
41
- - [Project Initialization](#project-initialization)
42
- - [Database Management](#database-management)
43
- - [Migration Management](#migration-management)
44
- - [Cache Management](#cache-management)
45
- - [Data Export/Import](#data-exportimport)
46
- - [Interactive REPL](#interactive-repl)
47
- 10. [Data Seeder](#-data-seeder)
48
- 11. [Function Modules in Depth](#-function-modules-in-depth)
49
- - [TOON Module](#toon-module)
50
- - [Math & Statistics](#math-module)
51
- - [String & Slug Module](#string-module)
52
- - [Array & Collection Module](#array-module)
53
- - [AI Module](#ai-module)
54
- - [Security & Cryptography](#security-cryptography)
55
- 12. [Validation & Sanitization Engine](#-validation--sanitization-engine)
56
- 13. [Professional Logger Pro](#-professional-logger-pro)
57
- 14. [HTTP & Networking](#-http--networking)
58
- 15. [Real-World Use Cases](#-real-world-use-cases)
59
- 16. [Frequently Asked Questions](#-frequently-asked-questions)
60
- 17. [Architecture & Performance Benchmarks](#-architecture--performance)
61
- 18. [Best Practices](#-best-practices)
62
- 19. [Troubleshooting](#-troubleshooting)
63
- 20. [License](#-license)
64
-
65
- ---
66
-
67
- ## 📦 Installation
9
+ ## Installation
68
10
 
69
11
  ```bash
70
12
  npm install @onurege3467/zerohelper
71
13
  ```
72
14
 
73
- ---
74
-
75
- ## 🛡️ TypeScript Excellence
76
-
77
- ZeroHelper 10.2.6 leverages **Discriminated Unions** to ensure that your configuration object perfectly matches your selected adapter. This eliminates the "configuration guesswork" that plagues most multi-database libraries.
78
-
79
- ### Example: Config Autocomplete
80
- ```typescript
81
- import { database } from '@onurege3467/zerohelper';
82
-
83
- const db = database.createDatabase({
84
- adapter: 'zpack',
85
- config: {
86
- path: './data.zpack',
87
- indexFields: { 'users': ['email'] },
88
- autoFlush: true
89
- }
90
- });
91
- ```
92
-
93
- ---
94
-
95
- ## 💾 Database Unified API
96
-
97
- All adapters implement the `IDatabase` interface, allowing you to swap database backends without changing a single line of your business logic.
98
-
99
- ### 📝 Common Operations
100
-
101
- #### 1. Inserting Data
102
- ```typescript
103
- const newId = await db.insert('users', {
104
- username: 'onurege',
105
- email: 'contact@onurege.com',
106
- created_at: new Date()
107
- });
108
-
109
- const count = await db.bulkInsert('logs', [
110
- { message: 'System Start', level: 'info' },
111
- { message: 'Database Connected', level: 'info' }
112
- ]);
113
- ```
114
-
115
- #### 2. Advanced Selection
116
- ```typescript
117
- interface User { _id: number; username: string; email: string; }
118
- const user = await db.selectOne<User>('users', { username: 'onurege' });
119
- ```
120
-
121
- #### 3. Atomic Counters
122
- ```typescript
123
- await db.increment('wallets', { balance: 100 }, { user_id: 1 });
124
- await db.decrement('inventory', { stock: 1 }, { sku: 'PRO-123' });
125
- ```
126
-
127
- #### 4. Upsert Operations
128
- ```typescript
129
- await db.set('settings', { value: 'dark' }, { key: 'theme' });
130
- ```
131
-
132
- ---
133
-
134
- ## 🚀 Specialized Database Adapters
135
-
136
- ### 🏎️ ZPack (The Binary Powerhouse)
137
-
138
- ZPack is ZeroHelper's proprietary binary format engineered for **maximum write performance** and **minimum storage footprint**.
139
-
140
- #### Key Features
141
- - **Ultra-Fast Writes**: 0.08ms average write latency
142
- - **zlib Compression**: 40-60% smaller file sizes
143
- - **Vacuum Operation**: Eliminate fragmentation from deleted records
144
- - **Secondary Indexing**: Instant lookups on indexed fields
145
- - **Auto-Flush**: Configurable write-through behavior
146
-
147
- #### When to Use ZPack
148
- - High-volume event logging
149
- - Audit trail storage
150
- - Data archival and backup
151
- - Time-series data (with vacuum maintenance)
152
-
153
- #### Example
154
- ```typescript
155
- const zpack = database.createDatabase({
156
- adapter: 'zpack',
157
- config: {
158
- path: './storage/events.zpack',
159
- indexFields: { 'events': ['event_type', 'user_id'] },
160
- autoFlush: true
161
- }
162
- });
163
-
164
- await zpack.insert('logs', { timestamp: new Date(), level: 'info', message: 'Event' });
165
-
166
- await zpack.vacuum();
167
- ```
168
-
169
- ### 📊 TOON (World's First Native TOON Database)
170
-
171
- ZeroHelper introduces the **world's first native TOON (Token-Oriented Object Notation) database** - a revolutionary format optimized for both humans and AI.
172
-
173
- #### Why TOON?
174
-
175
- | Feature | JSON | YAML | TOON |
176
- |---------|------|------|------|
177
- | Human Readable | ⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
178
- | Parse Speed | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
179
- | Token Efficiency | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
180
- | AI-Optimized | ❌ | ❌ | ⭐⭐⭐⭐⭐ |
181
- | File Size | Medium | Large | Small |
182
-
183
- #### TOON Syntax Example
184
- ```toon
185
- users:
186
- name: John
187
- age: 25
188
- active: true
189
-
190
- products:
191
- [3]{name,price,stock}:
192
- Laptop,1500,10
193
- Mouse,25,100
194
- Keyboard,75,50
195
- ```
196
-
197
- #### LLM Token Savings
198
- ```
199
- JSON: {"users":[{"name":"John","age":25,"active":true}]} = 47 tokens
200
- TOON: users: name: John age: 25 active: true = 12 tokens
201
-
202
- Savings: ~75% reduction in token usage!
203
- ```
204
-
205
- #### Use Cases
206
- - AI/LLM application data storage
207
- - Configuration files
208
- - Prompt engineering templates
209
- - Agent memory and context
210
-
211
- #### Example
212
- ```typescript
213
- const toonDb = database.createDatabase({
214
- adapter: 'toon',
215
- config: {
216
- path: './ai-data.toon',
217
- saveInterval: 1000
218
- }
219
- });
220
-
221
- await toonDb.insert('prompts', { system: 'You are helpful...', temperature: 0.7 });
222
- ```
223
-
224
- ### 🐘 PostgreSQL & 🐬 MySQL
225
-
226
- Enterprise-grade SQL adapters with automatic schema evolution.
227
- - **Auto-Table/Column Creation**: ZeroHelper creates missing tables and performs `ALTER TABLE` automatically when new keys are detected in your data.
228
-
229
- ### 🍃 MongoDB & 💚 Redis
230
-
231
- Flexible NoSQL adapters for document storage and caching.
232
-
233
- ---
234
-
235
- ## ⚡ Advanced Caching Layer
236
-
237
- Supports **Local LRU Memory** and **Remote Redis**. It automatically invalidates cache on writes.
238
-
239
- ```typescript
240
- const db = database.createDatabase({
241
- adapter: 'mysql',
242
- config: {
243
- host: 'localhost',
244
- cache: {
245
- type: 'redis',
246
- host: '127.0.0.1',
247
- ttl: 300000
248
- }
249
- }
250
- });
251
- ```
252
-
253
- ---
254
-
255
- ## 🪝 Database Lifecycle Hooks
256
-
257
- Register global hooks to monitor or modify data flow.
258
- ```typescript
259
- db.on('beforeInsert', (table, data) => {
260
- console.log(`Inserting into ${table}...`);
261
- data.updated_at = Date.now();
262
- });
263
-
264
- db.on('afterUpdate', (table, result) => {
265
- console.log(`Table ${table} updated. Rows affected: ${result.affected}`);
266
- });
267
- ```
268
-
269
- ---
270
-
271
- ## 📊 Telemetry & Performance Tracking
272
-
273
- Monitor your system health and operation latencies in real-time.
274
- ```typescript
275
- const metrics = db.getMetrics();
276
- console.log(`Avg Database Latency: ${metrics.database.averageDuration}`);
277
- console.log(`Cache Hit Ratio: ${metrics.cache.ratio}`);
278
- ```
279
-
280
- ---
281
-
282
- ## 📂 Database Migration System
283
-
284
- A professional workflow for schema changes.
285
- ```typescript
286
- const migration = new database.MigrationManager(db);
287
- migration.createMigration('add_profile_pictures');
288
- await migration.migrate();
289
- ```
290
-
291
- ---
292
-
293
- ## 🧵 ZeroWorker (Worker Threads)
15
+ ## Usage
294
16
 
295
- Run heavy CPU-bound tasks in the background without blocking the event loop.
296
17
  ```typescript
297
- import { functions } from '@onurege3467/zerohelper';
298
-
299
- const result = await functions.worker_module.runAsyncTask(
300
- "(data) => { return data.map(x => x * 2); }",
301
- [1, 2, 3]
302
- );
303
- ```
304
-
305
- ---
306
-
307
- ## 🛠️ Zero-CLI
308
-
309
- A professional command-line interface to manage your database and ZeroHelper framework.
310
-
311
- ### 📋 Available Commands
312
-
313
- #### **Project Initialization**
314
- ```bash
315
- npx zero init
316
- ```
317
-
318
- #### **Database Management**
319
- ```bash
320
- npx zero db:test
321
- npx zero db:stats
322
- npx zero db:seed --table users --count 100
323
- npx zero db:backup
324
- npx zero db:backup --output ./custom-backups
325
- npx zero db:restore ./backups/backup_2024-01-01.zerohelper.json
326
- ```
327
-
328
- #### **Migration Management**
329
- ```bash
330
- npx zero migrate
331
- npx zero migration:rollback --steps 1
332
- npx zero migration:status
333
- npx zero make:migration create_users_table
18
+ import { database, functions } from '@onurege3467/zerohelper';
334
19
  ```
335
20
 
336
- #### **Cache Management**
337
- ```bash
338
- npx zero cache:clear
339
- npx zero cache:stats
340
- ```
341
-
342
- #### **Data Export/Import**
343
- ```bash
344
- npx zero db:export --table users --format json
345
- npx zero db:export --table users --format csv --output ./exports/users.csv
346
- npx zero db:import ./exports/users.csv --table users --format csv
347
- npx zero db:import ./exports/users.json --table users --format json
348
- ```
349
-
350
- #### **ZPack Maintenance**
351
- ```bash
352
- npx zero zpack:vacuum ./data.zpack
353
- ```
354
-
355
- #### **Interactive REPL**
356
- ```bash
357
- npx zero repl
358
- ```
359
- **Available REPL commands:**
360
- - `.exit` - Exit REPL
361
- - `.help` - Show available commands
362
- - `.stats` - Show database stats
363
- - `.metrics` - Show performance metrics
364
- - `.clear` - Clear screen
365
- - `select <table>` - Select all from table
366
- - `count <table>` - Count records in table
367
-
368
- #### **Global Options**
369
- - `-c, --config <path>` - Path to config file (default: `zero.config.ts`)
370
- - `-h, --help` - Show help for command
371
- - `-V, --version` - Output version number
372
-
373
- ---
374
-
375
- ## 📥 Data Seeder
376
-
377
- Populate your database with realistic mock data in seconds.
378
-
379
- ### Programmatic Usage
380
- ```typescript
381
- const seeder = new database.DataSeeder(db);
382
- await seeder.seed('users', 100, {
383
- email: { type: 'email' },
384
- age: { type: 'number', min: 18, max: 65 },
385
- isActive: { type: 'boolean' }
386
- });
387
- ```
388
-
389
- ### CLI Usage
390
- ```bash
391
- npx zero db:seed --table users --count 100
392
- ```
393
-
394
- ### Supported Field Types
395
- - `string` - Random string with configurable length
396
- - `number` - Random number within min/max range
397
- - `email` - Random email address with various domains
398
- - `boolean` - Random true/false value
399
- - `date` - Random date within the last decade
400
- - `id` - Unique ID string
401
- - `pick` - Random value from provided array
402
-
403
- ---
404
-
405
- ## 🛠️ Function Modules in Depth
406
-
407
- ### 📄 TOON Module
408
- Standard API matching the native `JSON` object for zero learning curve.
409
- ```typescript
410
- import { functions } from '@onurege3467/zerohelper';
411
-
412
- const str = functions.toon_module.stringify({ a: 1, b: 2 });
413
- const obj = functions.toon_module.parse(str);
414
- ```
415
-
416
- ### 🔢 Math & Statistics (`math_module`)
417
- ```typescript
418
- const data = [10, 2, 38, 23, 21];
419
- functions.math_module.mean(data);
420
- functions.math_module.standardDeviation(data);
421
- functions.math_module.isPrime(13);
422
- ```
423
-
424
- ### 🔤 String & Slug Module (`string_module`)
425
- ```typescript
426
- functions.string_module.generateSlug("ZeroHelper: The Best!");
427
- functions.string_module.titleCase("hello world");
428
- ```
429
-
430
- ### 🎲 Random Module (`random_module`)
431
- ```typescript
432
- functions.random_module.makeUniqueId();
433
- functions.random_module.randomHex();
434
- functions.random_module.randomEmoji();
435
- ```
436
-
437
- ### 🌐 HTTP Module (`http_module`)
438
- ```typescript
439
- const data = await functions.http_module.fetchData('https://api.example.com/data');
440
- const response = await functions.http_module.postData('https://api.example.com/post', { key: 'value' });
441
- ```
442
-
443
- ### 📅 Date Module (`date_module`)
444
- ```typescript
445
- functions.date_module.formatDate(new Date(), 'YYYY-MM-DD');
446
- functions.date_module.addDays(new Date(), 5);
447
- functions.date_module.dateDifference(date1, date2);
448
- ```
449
-
450
- ### 🛠️ Array Module (`array_module`)
451
- ```typescript
452
- functions.array_module.shuffleArray([1, 2, 3, 4, 5]);
453
- functions.array_module.groupBy(users, 'role');
454
- functions.array_module.pluck(users, 'email');
455
- functions.array_module.sortBy(users, 'name');
456
- ```
457
-
458
- ### 🔧 Object Module (`object_module`)
459
- ```typescript
460
- functions.object_module.deepMerge(obj1, obj2);
461
- functions.object_module.filterObjectByKey(obj, ['name', 'email']);
462
- ```
463
-
464
- ### 🤖 AI Module (`ai_module`)
465
-
466
- LLM/AI çalışmaları için yardımcı utility fonksiyonları. Token hesaplama, prompt yönetimi, maliyet tahmini ve context optimizasyonu.
467
-
468
- #### Token İşlemleri
469
- ```typescript
470
- // Yaklaşık token sayısı hesaplama
471
- const tokens = functions.ai_module.estimateTokens("Hello world this is a test");
472
-
473
- // Metni token limitine göre kırpma
474
- const truncated = functions.ai_module.truncateToTokenLimit(longText, 1000);
475
-
476
- // Metni parçalara bölme
477
- const chunks = functions.ai_module.splitByTokenLimit(longText, 4000);
478
- ```
479
-
480
- #### Prompt Yönetimi
481
- ```typescript
482
- // Chat mesajı formatlama
483
- const message = functions.ai_module.formatChatMessage('user', 'Hello');
484
-
485
- // Few-shot prompt oluşturma
486
- const prompt = functions.ai_module.createFewShotPrompt([
487
- { input: '2+2?', output: '4' },
488
- { input: '3+3?', output: '6' }
489
- ], '4+4?');
490
-
491
- // Sistem ve kullanıcı mesajlarını birleştirme
492
- const messages = functions.ai_module.mergeSystemAndUser(
493
- 'You are a helpful assistant',
494
- 'What is the weather?'
495
- );
496
- ```
497
-
498
- #### Context & Conversation Yönetimi
499
- ```typescript
500
- // Mesajları context penceresine sığdırma
501
- const fitted = functions.ai_module.fitMessagesToContext(messages, 8000);
502
-
503
- // Konuşma geçmişini sıkıştırma
504
- const compressed = functions.ai_module.compressConversationHistory(messages, 4);
505
- ```
506
-
507
- #### Maliyet Hesaplama
508
- ```typescript
509
- // Konuşma maliyetini tahmin etme
510
- const cost = functions.ai_module.estimateConversationCost(messages, 'gpt-4');
511
- console.log(cost.totalCost); // USD cinsinden toplam maliyet
512
-
513
- // Model bilgileri
514
- const limit = functions.ai_module.getModelTokenLimit('gpt-4o'); // 128000
515
- const pricing = functions.ai_module.getModelPricing('claude-3-sonnet');
516
- ```
517
-
518
- #### Output İşlemleri
519
- ```typescript
520
- // Markdown'dan JSON çıkarma
521
- const json = functions.ai_module.extractJSONFromMarkdown('```json\n{"key": "value"}\n```');
522
-
523
- // Streaming response parse etme
524
- const chunk = functions.ai_module.parseStreamingChunk('data: {"choices": [{"delta": {"content": "Hello"}}]}');
525
- ```
526
-
527
- #### Utility Fonksiyonlar
528
- ```typescript
529
- // Token limit kontrolü
530
- if (functions.ai_module.isTokenLimitExceeded(prompt, 4000)) {
531
- // Prompt çok uzun
532
- }
533
-
534
- // Yüzdeye göre kısaltma
535
- const shorter = functions.ai_module.truncatePromptByPercentage(prompt, 50); // %50 kısalt
536
- ```
537
-
538
- ---
539
-
540
- ## 🔐 Security & Cryptography
541
-
542
- ### Password Handling
543
- ```typescript
544
- const hash = functions.crypto_module.hashPassword('securePassword123');
545
- const isValid = functions.crypto_module.verifyPassword('securePassword123', hash);
546
- ```
547
-
548
- ### Text Encryption (AES-256-CBC)
549
- ```typescript
550
- const { encryptedText, iv } = functions.crypto_module.encryptText('secret', 'mySecretKey');
551
- const original = functions.crypto_module.decryptText(encryptedText, 'mySecretKey', iv);
552
- ```
553
-
554
- ### JWT Tokens
555
- ```typescript
556
- const token = functions.crypto_module.generateJWT({ userId: 1 }, 'jwtSecret');
557
- const payload = functions.crypto_module.verifyJWT(token, 'jwtSecret');
558
- ```
559
-
560
- ### Rate Limiting
561
-
562
- #### Memory-based (Single Instance)
563
- ```typescript
564
- const result = await functions.security_module.checkRateLimit('user:1', {
565
- limit: 10,
566
- window: 60,
567
- storage: 'memory'
568
- });
569
- console.log(result.allowed); // true or false
570
- ```
571
-
572
- #### Redis-based (Distributed Systems)
573
- ```typescript
574
- const result = await functions.security_module.checkRateLimit('api:192.168.1.1', {
575
- limit: 100,
576
- window: 60,
577
- storage: 'redis',
578
- redisClient: redisDb
579
- });
580
- ```
581
-
582
- ### Additional Security Functions
583
- ```typescript
584
- functions.crypto_module.isPasswordStrong('MySecureP@ss123');
585
- functions.crypto_module.validateUUID('550e8400-e29b-41d4-a716-446655440000');
586
- functions.crypto_module.generateSalt();
587
- ```
588
-
589
- ---
590
-
591
- ## 🛡️ Validation & Sanitization Engine
592
-
593
- ### Schema Validation
594
- ```typescript
595
- const schema = {
596
- email: { required: true, type: 'string', pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
597
- age: { required: false, type: 'number', min: 18, max: 120 },
598
- password: { required: true, type: 'string', minLength: 8 }
599
- };
600
-
601
- const result = functions.validation_module.validateSchema(data, schema);
602
- console.log(result.isValid);
603
- console.log(result.errors);
604
- ```
605
-
606
- ### Input Sanitization
607
- ```typescript
608
- const clean = functions.validation_module.sanitizeInput(userInput, {
609
- trim: true,
610
- removeHTML: true,
611
- escape: true
612
- });
613
- ```
614
-
615
- ### Utilities
616
- ```typescript
617
- functions.validation_module.isEmail('test@example.com');
618
- functions.validation_module.isPhone('+1234567890');
619
- functions.validation_module.isURL('https://example.com');
620
- functions.validation_module.sanitizeHTML('<script>alert("xss")</script>');
621
- functions.validation_module.validateCreditCard('4111111111111111');
622
- ```
623
-
624
- ---
625
-
626
- ## 📝 Professional Logger Pro
627
-
628
- ```typescript
629
- import { functions } from '@onurege3467/zerohelper';
630
-
631
- const logger = functions.logger_module.createLogger({
632
- level: 'info',
633
- enableColors: true,
634
- enableTimestamp: true,
635
- logFile: './app.log'
636
- });
637
-
638
- logger.info('User logged in', { userId: 123 });
639
- logger.warn('Rate limit approaching', { remaining: 10 });
640
- logger.error('Database connection failed', { error: err.message });
641
- logger.debug('Cache hit', { key: 'user:123' });
642
- ```
643
-
644
- ### Quick Logging Functions
645
- ```typescript
646
- functions.logger_module.info('Message');
647
- functions.logger_module.warn('Message');
648
- functions.logger_module.error('Message');
649
- functions.logger_module.debug('Message');
650
- ```
651
-
652
- ---
653
-
654
- ## 🏎️ Performance Benchmarks
655
- *Hardware: Intel i9-12900K, 64GB RAM*
656
- - **ZPack Binary Write:** 0.08ms
657
- - **TOON Serialization:** 0.15ms / 1KB
658
- - **Array Grouping (1M items):** 45ms
659
-
660
- ---
661
-
662
- ## 🎯 Real-World Use Cases
663
-
664
- ### E-Commerce Application
665
- ```typescript
666
- const db = database.createDatabase({
667
- adapter: 'postgres',
668
- config: {
669
- host: 'localhost',
670
- user: 'admin',
671
- password: 'secure',
672
- database: 'shop',
673
- cache: { type: 'redis', host: '127.0.0.1', ttl: 300000 }
674
- }
675
- });
676
-
677
- await db.insert('products', { name: 'Laptop', price: 1500, stock: 10 });
678
- await db.decrement('products', { stock: 1 }, { sku: 'PROD-001' });
679
- await db.increment('orders', { total: 1500 }, { orderId: 1001 });
680
-
681
- const hash = functions.crypto_module.hashPassword(userPassword);
682
- await db.insert('users', { email, password: hash });
683
- ```
684
-
685
- ### AI/LLM Applications with TOON
686
- ```typescript
687
- const toonDb = database.createDatabase({
688
- adapter: 'toon',
689
- config: { path: './ai-data.toon' }
690
- });
691
-
692
- await toonDb.insert('prompts', {
693
- system: 'You are a helpful assistant designed for customer support.',
694
- examples: [...],
695
- temperature: 0.7,
696
- maxTokens: 1000
697
- });
698
-
699
- const prompts = toonDb.select('prompts', { category: 'support' });
700
- ```
701
-
702
- ### High-Performance Logging with ZPack
703
- ```typescript
704
- const zpack = database.createDatabase({
705
- adapter: 'zpack',
706
- config: { path: './logs.zpack', autoFlush: true }
707
- });
708
-
709
- await zpack.insert('events', {
710
- timestamp: new Date(),
711
- level: 'info',
712
- message: 'User action recorded',
713
- userId: 123,
714
- action: 'purchase',
715
- amount: 99.99
716
- });
717
-
718
- await zpack.vacuum();
719
- ```
720
-
721
- ### Distributed API Protection
722
- ```typescript
723
- import { database } from '@onurege3467/zerohelper';
724
-
725
- const redisDb = database.createDatabase({
726
- adapter: 'redis',
727
- config: { host: '127.0.0.1', port: 6379 }
728
- });
729
-
730
- async function handleApiRequest(ip: string) {
731
- const rateLimit = await functions.security_module.checkRateLimit(`api:${ip}`, {
732
- limit: 1000,
733
- window: 3600,
734
- storage: 'redis',
735
- redisClient: redisDb
736
- });
737
-
738
- if (!rateLimit.allowed) {
739
- throw new Error('Rate limit exceeded');
740
- }
741
-
742
- return processRequest();
743
- }
744
- ```
745
-
746
- ---
747
-
748
- ## ❓ Frequently Asked Questions
749
-
750
- ### Q: Which adapter should I choose?
751
-
752
- **A:**
753
- - **ZPack**: High-volume logging, archival, audit trails
754
- - **TOON**: AI/LLM applications, configs, human-readable needs
755
- - **JSON**: Development, small projects, prototyping
756
- - **SQLite**: Desktop apps, single-user applications
757
- - **PostgreSQL/MySQL**: Web applications, enterprise systems
758
- - **MongoDB**: Flexible document schemas, content management
759
- - **Redis**: Caching, sessions, real-time features
760
-
761
- ### Q: How does TOON save tokens for LLMs?
762
-
763
- **A:** TOON uses compact syntax like `[3]{name,age}: John,25 Jane,30 Bob,28` instead of verbose JSON arrays. This reduces token count by 30-60% while maintaining full data fidelity and human readability.
764
-
765
- ### Q: Is ZPack suitable for concurrent access?
766
-
767
- **A:** ZPack is optimized for single-writer scenarios. For multi-threaded logging, consider using SQLite or a dedicated logging service with ZPack for archival.
768
-
769
- ### Q: Can I migrate between adapters?
770
-
771
- **A:** Yes! All adapters implement the IDatabase interface. Export data using `db:export` CLI command and import to any other adapter.
772
-
773
- ### Q: What's the difference between memory and Redis rate limiting?
774
-
775
- **A:** Memory storage is fast and suitable for single-instance applications. Redis storage enables distributed rate limiting across multiple server instances.
776
-
777
- ### Q: Does ZeroHelper support transactions?
778
-
779
- **A:** SQL adapters (PostgreSQL, MySQL, SQLite) support transactions. NoSQL and file-based adapters have atomic operations but not full ACID transactions.
780
-
781
- ---
782
-
783
- ## 🏁 Final Words
784
-
785
- **ZeroHelper** is the result of years of private commercial development, now open for the community to build the next generation of high-performance Node.js applications.
786
-
787
- Developed with ❤️ by **Onure9e**. Built for excellence.
788
-
789
- ---
790
-
791
- ## 📜 License
21
+ ## License
792
22
 
793
- Licensed under the [ISC License](LICENSE).
23
+ ISC