@onurege3467/zerohelper 10.2.5 → 10.3.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 +507 -54
- package/dist/bin/commands/cache.d.ts +2 -0
- package/dist/bin/commands/cache.js +92 -0
- package/dist/bin/commands/db-backup.d.ts +3 -0
- package/dist/bin/commands/db-backup.js +118 -0
- package/dist/bin/commands/db.d.ts +2 -0
- package/dist/bin/commands/db.js +334 -0
- package/dist/bin/commands/import-export.d.ts +3 -0
- package/dist/bin/commands/import-export.js +123 -0
- package/dist/bin/commands/init.d.ts +2 -0
- package/dist/bin/commands/init.js +85 -0
- package/dist/bin/commands/migrate.d.ts +3 -0
- package/dist/bin/commands/migrate.js +167 -0
- package/dist/bin/commands/repl.d.ts +2 -0
- package/dist/bin/commands/repl.js +96 -0
- package/dist/bin/commands/seed.d.ts +2 -0
- package/dist/bin/commands/seed.js +76 -0
- package/dist/bin/commands/zpack.d.ts +2 -0
- package/dist/bin/commands/zpack.js +36 -0
- package/dist/bin/index.d.ts +2 -0
- package/dist/bin/index.js +28 -0
- package/dist/bin/types.d.ts +22 -0
- package/dist/bin/types.js +2 -0
- package/dist/bin/utils/config.d.ts +3 -0
- package/dist/bin/utils/config.js +78 -0
- package/dist/bin/utils/prompts.d.ts +3 -0
- package/dist/bin/utils/prompts.js +115 -0
- package/dist/bin/zero.js +789 -81
- package/dist/functions/ai.d.ts +126 -0
- package/dist/functions/ai.js +387 -0
- package/dist/functions/index.d.ts +24 -0
- package/dist/functions/index.js +5 -1
- package/dist/migrations/1767521950635_test_migration.d.ts +3 -0
- package/dist/migrations/1767521950635_test_migration.js +11 -0
- package/dist/migrations/1767522158826_create_users_table.d.ts +2 -0
- package/dist/migrations/1767522158826_create_users_table.js +11 -0
- package/dist/package.json +79 -0
- package/dist/zero.config.d.ts +10 -0
- package/dist/zero.config.js +13 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://www.typescriptlang.org/)
|
|
5
5
|
[](https://opensource.org/licenses/ISC)
|
|
6
6
|
|
|
7
|
-
**ZeroHelper** is an elite-level, high-performance, and fully TypeScript-native utility ecosystem. Rebuilt from the ground up for version
|
|
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.
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
@@ -38,20 +38,29 @@ We have now decided to open the vault. By open-sourcing this battle-hardened fra
|
|
|
38
38
|
7. [Database Migration System](#-database-migration-system)
|
|
39
39
|
8. [ZeroWorker (Worker Threads)](#-zeroworker-worker-threads)
|
|
40
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)
|
|
41
47
|
10. [Data Seeder](#-data-seeder)
|
|
42
48
|
11. [Function Modules in Depth](#-function-modules-in-depth)
|
|
43
49
|
- [TOON Module](#toon-module)
|
|
44
50
|
- [Math & Statistics](#math-module)
|
|
45
51
|
- [String & Slug Module](#string-module)
|
|
46
52
|
- [Array & Collection Module](#array-module)
|
|
53
|
+
- [AI Module](#ai-module)
|
|
47
54
|
- [Security & Cryptography](#security-cryptography)
|
|
48
55
|
12. [Validation & Sanitization Engine](#-validation--sanitization-engine)
|
|
49
56
|
13. [Professional Logger Pro](#-professional-logger-pro)
|
|
50
57
|
14. [HTTP & Networking](#-http--networking)
|
|
51
|
-
15. [
|
|
52
|
-
16. [
|
|
53
|
-
17. [
|
|
54
|
-
18. [
|
|
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)
|
|
55
64
|
|
|
56
65
|
---
|
|
57
66
|
|
|
@@ -65,18 +74,17 @@ npm install @onurege3467/zerohelper
|
|
|
65
74
|
|
|
66
75
|
## 🛡️ TypeScript Excellence
|
|
67
76
|
|
|
68
|
-
ZeroHelper
|
|
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.
|
|
69
78
|
|
|
70
79
|
### Example: Config Autocomplete
|
|
71
80
|
```typescript
|
|
72
81
|
import { database } from '@onurege3467/zerohelper';
|
|
73
82
|
|
|
74
|
-
// Type-Safe Factory
|
|
75
83
|
const db = database.createDatabase({
|
|
76
84
|
adapter: 'zpack',
|
|
77
85
|
config: {
|
|
78
86
|
path: './data.zpack',
|
|
79
|
-
indexFields: { 'users': ['email'] },
|
|
87
|
+
indexFields: { 'users': ['email'] },
|
|
80
88
|
autoFlush: true
|
|
81
89
|
}
|
|
82
90
|
});
|
|
@@ -92,14 +100,12 @@ All adapters implement the `IDatabase` interface, allowing you to swap database
|
|
|
92
100
|
|
|
93
101
|
#### 1. Inserting Data
|
|
94
102
|
```typescript
|
|
95
|
-
// Simple insert
|
|
96
103
|
const newId = await db.insert('users', {
|
|
97
104
|
username: 'onurege',
|
|
98
105
|
email: 'contact@onurege.com',
|
|
99
106
|
created_at: new Date()
|
|
100
107
|
});
|
|
101
108
|
|
|
102
|
-
// Bulk insert (Highly optimized)
|
|
103
109
|
const count = await db.bulkInsert('logs', [
|
|
104
110
|
{ message: 'System Start', level: 'info' },
|
|
105
111
|
{ message: 'Database Connected', level: 'info' }
|
|
@@ -108,60 +114,121 @@ const count = await db.bulkInsert('logs', [
|
|
|
108
114
|
|
|
109
115
|
#### 2. Advanced Selection
|
|
110
116
|
```typescript
|
|
111
|
-
// Fetch a single record with generic types
|
|
112
117
|
interface User { _id: number; username: string; email: string; }
|
|
113
118
|
const user = await db.selectOne<User>('users', { username: 'onurege' });
|
|
114
119
|
```
|
|
115
120
|
|
|
116
121
|
#### 3. Atomic Counters
|
|
117
|
-
Avoid race conditions by using atomic operations instead of manual fetching and saving.
|
|
118
122
|
```typescript
|
|
119
|
-
// Safely incrementing balance
|
|
120
123
|
await db.increment('wallets', { balance: 100 }, { user_id: 1 });
|
|
121
|
-
|
|
122
|
-
// Safely decrementing stock
|
|
123
124
|
await db.decrement('inventory', { stock: 1 }, { sku: 'PRO-123' });
|
|
124
125
|
```
|
|
125
126
|
|
|
127
|
+
#### 4. Upsert Operations
|
|
128
|
+
```typescript
|
|
129
|
+
await db.set('settings', { value: 'dark' }, { key: 'theme' });
|
|
130
|
+
```
|
|
131
|
+
|
|
126
132
|
---
|
|
127
133
|
|
|
128
134
|
## 🚀 Specialized Database Adapters
|
|
129
135
|
|
|
130
136
|
### 🏎️ ZPack (The Binary Powerhouse)
|
|
131
|
-
**ZPack** is ZeroHelper's proprietary binary format designed for high-throughput logging and data archival.
|
|
132
|
-
- **Vacuum:** `await db.vacuum()` - Rebuilds the file to eliminate fragmented space from deleted records.
|
|
133
|
-
- **Indexing:** Instant lookups on non-ID fields using secondary indexing.
|
|
134
|
-
- **Compression:** Built-in `zlib` compression for minimal disk footprint.
|
|
135
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
|
|
136
154
|
```typescript
|
|
137
155
|
const zpack = database.createDatabase({
|
|
138
156
|
adapter: 'zpack',
|
|
139
|
-
config: {
|
|
157
|
+
config: {
|
|
158
|
+
path: './storage/events.zpack',
|
|
159
|
+
indexFields: { 'events': ['event_type', 'user_id'] },
|
|
160
|
+
autoFlush: true
|
|
161
|
+
}
|
|
140
162
|
});
|
|
163
|
+
|
|
164
|
+
await zpack.insert('logs', { timestamp: new Date(), level: 'info', message: 'Event' });
|
|
165
|
+
|
|
166
|
+
await zpack.vacuum();
|
|
141
167
|
```
|
|
142
168
|
|
|
143
|
-
### 📊 TOON (
|
|
144
|
-
The **world's first native TOON database**. It stores data in a YAML-like compact format optimized for LLMs and human readability.
|
|
169
|
+
### 📊 TOON (World's First Native TOON Database)
|
|
145
170
|
|
|
146
|
-
|
|
147
|
-
- **Token Efficiency:** Saves **30-60% tokens** when your AI agents read your data files.
|
|
148
|
-
- **Readable Alternative:** As fast as binary but as readable as YAML.
|
|
171
|
+
ZeroHelper introduces the **world's first native TOON (Token-Oriented Object Notation) database** - a revolutionary format optimized for both humans and AI.
|
|
149
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
|
|
150
212
|
```typescript
|
|
151
213
|
const toonDb = database.createDatabase({
|
|
152
214
|
adapter: 'toon',
|
|
153
215
|
config: {
|
|
154
|
-
path: './data.toon',
|
|
155
|
-
saveInterval: 1000
|
|
216
|
+
path: './ai-data.toon',
|
|
217
|
+
saveInterval: 1000
|
|
156
218
|
}
|
|
157
219
|
});
|
|
158
220
|
|
|
159
|
-
await toonDb.insert('
|
|
221
|
+
await toonDb.insert('prompts', { system: 'You are helpful...', temperature: 0.7 });
|
|
160
222
|
```
|
|
161
223
|
|
|
162
224
|
### 🐘 PostgreSQL & 🐬 MySQL
|
|
225
|
+
|
|
163
226
|
Enterprise-grade SQL adapters with automatic schema evolution.
|
|
164
|
-
- **Auto-Table/Column Creation
|
|
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.
|
|
165
232
|
|
|
166
233
|
---
|
|
167
234
|
|
|
@@ -177,7 +244,7 @@ const db = database.createDatabase({
|
|
|
177
244
|
cache: {
|
|
178
245
|
type: 'redis',
|
|
179
246
|
host: '127.0.0.1',
|
|
180
|
-
ttl: 300000
|
|
247
|
+
ttl: 300000
|
|
181
248
|
}
|
|
182
249
|
}
|
|
183
250
|
});
|
|
@@ -195,7 +262,7 @@ db.on('beforeInsert', (table, data) => {
|
|
|
195
262
|
});
|
|
196
263
|
|
|
197
264
|
db.on('afterUpdate', (table, result) => {
|
|
198
|
-
|
|
265
|
+
console.log(`Table ${table} updated. Rows affected: ${result.affected}`);
|
|
199
266
|
});
|
|
200
267
|
```
|
|
201
268
|
|
|
@@ -239,26 +306,77 @@ const result = await functions.worker_module.runAsyncTask(
|
|
|
239
306
|
|
|
240
307
|
## 🛠️ Zero-CLI
|
|
241
308
|
|
|
242
|
-
A professional command-line interface to manage your framework.
|
|
309
|
+
A professional command-line interface to manage your database and ZeroHelper framework.
|
|
310
|
+
|
|
311
|
+
### 📋 Available Commands
|
|
312
|
+
|
|
313
|
+
#### **Project Initialization**
|
|
243
314
|
```bash
|
|
244
|
-
# Initialize project interactively
|
|
245
315
|
npx zero init
|
|
316
|
+
```
|
|
246
317
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
# View real-time DB dashboard
|
|
318
|
+
#### **Database Management**
|
|
319
|
+
```bash
|
|
320
|
+
npx zero db:test
|
|
251
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
|
|
334
|
+
```
|
|
335
|
+
|
|
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
|
+
```
|
|
252
354
|
|
|
253
|
-
|
|
254
|
-
|
|
355
|
+
#### **Interactive REPL**
|
|
356
|
+
```bash
|
|
357
|
+
npx zero repl
|
|
255
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
|
|
256
372
|
|
|
257
373
|
---
|
|
258
374
|
|
|
259
375
|
## 📥 Data Seeder
|
|
260
376
|
|
|
261
377
|
Populate your database with realistic mock data in seconds.
|
|
378
|
+
|
|
379
|
+
### Programmatic Usage
|
|
262
380
|
```typescript
|
|
263
381
|
const seeder = new database.DataSeeder(db);
|
|
264
382
|
await seeder.seed('users', 100, {
|
|
@@ -268,6 +386,20 @@ await seeder.seed('users', 100, {
|
|
|
268
386
|
});
|
|
269
387
|
```
|
|
270
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
|
+
|
|
271
403
|
---
|
|
272
404
|
|
|
273
405
|
## 🛠️ Function Modules in Depth
|
|
@@ -284,38 +416,238 @@ const obj = functions.toon_module.parse(str);
|
|
|
284
416
|
### 🔢 Math & Statistics (`math_module`)
|
|
285
417
|
```typescript
|
|
286
418
|
const data = [10, 2, 38, 23, 21];
|
|
287
|
-
functions.math_module.mean(data);
|
|
288
|
-
functions.math_module.standardDeviation(data);
|
|
289
|
-
functions.math_module.isPrime(13);
|
|
419
|
+
functions.math_module.mean(data);
|
|
420
|
+
functions.math_module.standardDeviation(data);
|
|
421
|
+
functions.math_module.isPrime(13);
|
|
290
422
|
```
|
|
291
423
|
|
|
292
424
|
### 🔤 String & Slug Module (`string_module`)
|
|
293
425
|
```typescript
|
|
294
|
-
functions.string_module.generateSlug("ZeroHelper: The Best!");
|
|
295
|
-
functions.string_module.titleCase("hello world");
|
|
426
|
+
functions.string_module.generateSlug("ZeroHelper: The Best!");
|
|
427
|
+
functions.string_module.titleCase("hello world");
|
|
296
428
|
```
|
|
297
429
|
|
|
298
430
|
### 🎲 Random Module (`random_module`)
|
|
299
431
|
```typescript
|
|
300
|
-
functions.random_module.makeUniqueId();
|
|
301
|
-
functions.random_module.randomHex();
|
|
302
|
-
functions.random_module.randomEmoji();
|
|
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
|
|
303
536
|
```
|
|
304
537
|
|
|
305
538
|
---
|
|
306
539
|
|
|
307
540
|
## 🔐 Security & Cryptography
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
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
|
+
```
|
|
312
588
|
|
|
313
589
|
---
|
|
314
590
|
|
|
315
591
|
## 🛡️ Validation & Sanitization Engine
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
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
|
+
```
|
|
319
651
|
|
|
320
652
|
---
|
|
321
653
|
|
|
@@ -327,6 +659,127 @@ functions.random_module.randomEmoji(); // "🚀"
|
|
|
327
659
|
|
|
328
660
|
---
|
|
329
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
|
+
|
|
330
783
|
## 🏁 Final Words
|
|
331
784
|
|
|
332
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.
|