s3db.js 12.1.0 → 12.2.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 (42) hide show
  1. package/README.md +212 -196
  2. package/dist/s3db.cjs.js +1286 -226
  3. package/dist/s3db.cjs.js.map +1 -1
  4. package/dist/s3db.es.js +1284 -226
  5. package/dist/s3db.es.js.map +1 -1
  6. package/package.json +6 -1
  7. package/src/cli/index.js +954 -43
  8. package/src/cli/migration-manager.js +270 -0
  9. package/src/concerns/calculator.js +0 -4
  10. package/src/concerns/metadata-encoding.js +1 -21
  11. package/src/concerns/plugin-storage.js +17 -4
  12. package/src/concerns/typescript-generator.d.ts +171 -0
  13. package/src/concerns/typescript-generator.js +275 -0
  14. package/src/database.class.js +171 -28
  15. package/src/index.js +15 -9
  16. package/src/plugins/api/index.js +0 -1
  17. package/src/plugins/api/routes/resource-routes.js +86 -1
  18. package/src/plugins/api/server.js +79 -3
  19. package/src/plugins/api/utils/openapi-generator.js +195 -5
  20. package/src/plugins/backup/multi-backup-driver.class.js +0 -1
  21. package/src/plugins/backup.plugin.js +7 -14
  22. package/src/plugins/concerns/plugin-dependencies.js +73 -19
  23. package/src/plugins/eventual-consistency/analytics.js +0 -2
  24. package/src/plugins/eventual-consistency/consolidation.js +2 -13
  25. package/src/plugins/eventual-consistency/index.js +0 -1
  26. package/src/plugins/eventual-consistency/install.js +1 -1
  27. package/src/plugins/geo.plugin.js +5 -6
  28. package/src/plugins/importer/index.js +1 -1
  29. package/src/plugins/relation.plugin.js +11 -11
  30. package/src/plugins/replicator.plugin.js +12 -21
  31. package/src/plugins/s3-queue.plugin.js +4 -4
  32. package/src/plugins/scheduler.plugin.js +10 -12
  33. package/src/plugins/state-machine.plugin.js +8 -12
  34. package/src/plugins/tfstate/README.md +1 -1
  35. package/src/plugins/tfstate/errors.js +3 -3
  36. package/src/plugins/tfstate/index.js +41 -67
  37. package/src/plugins/ttl.plugin.js +3 -3
  38. package/src/resource.class.js +263 -61
  39. package/src/schema.class.js +0 -2
  40. package/src/testing/factory.class.js +286 -0
  41. package/src/testing/index.js +15 -0
  42. package/src/testing/seeder.class.js +183 -0
package/README.md CHANGED
@@ -186,6 +186,147 @@ console.log(`Total users: ${allUsers.length}`);
186
186
 
187
187
  **That's it!** You now have a fully functional document database running on AWS S3. 🎉
188
188
 
189
+ ### 5. Add plugins for a better experience (Optional)
190
+
191
+ Enhance your database with powerful plugins for production-ready features:
192
+
193
+ ```javascript
194
+ import { S3db, TTLPlugin, RelationPlugin, ReplicatorPlugin, CachePlugin } from "s3db.js";
195
+
196
+ const s3db = new S3db({
197
+ connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
198
+ plugins: [
199
+ // Auto-cleanup expired records (no cron jobs needed!)
200
+ new TTLPlugin({
201
+ resources: {
202
+ sessions: { ttl: 86400, onExpire: 'soft-delete' } // 24h
203
+ }
204
+ }),
205
+
206
+ // ORM-like relationships with 10-100x faster queries
207
+ new RelationPlugin({
208
+ relations: {
209
+ users: {
210
+ posts: { type: 'hasMany', resource: 'posts', foreignKey: 'userId' }
211
+ }
212
+ }
213
+ }),
214
+
215
+ // Real-time replication to BigQuery, PostgreSQL, etc.
216
+ new ReplicatorPlugin({
217
+ replicators: [{
218
+ driver: 'bigquery',
219
+ config: { projectId: 'my-project', datasetId: 'analytics' },
220
+ resources: { users: 'users_table', posts: 'posts_table' }
221
+ }]
222
+ }),
223
+
224
+ // Cache frequently accessed data (memory, S3, or filesystem)
225
+ new CachePlugin({
226
+ driver: 'memory',
227
+ ttl: 300000 // 5 minutes
228
+ })
229
+ ]
230
+ });
231
+ ```
232
+
233
+ **Learn more** about available plugins and their features in the [Plugin Documentation](docs/plugins/README.md).
234
+
235
+ ---
236
+
237
+ ## 📘 TypeScript Support
238
+
239
+ s3db.js includes comprehensive TypeScript definitions out of the box. Get full type safety, autocomplete, and IntelliSense support in your IDE!
240
+
241
+ ### Basic Usage (Automatic Types)
242
+
243
+ ```typescript
244
+ import { Database, DatabaseConfig, Resource } from 's3db.js';
245
+
246
+ // Type-safe configuration
247
+ const config: DatabaseConfig = {
248
+ connectionString: 's3://ACCESS_KEY:SECRET@bucket/path',
249
+ verbose: true,
250
+ parallelism: 10,
251
+ cache: { enabled: true, ttl: 3600 }
252
+ };
253
+
254
+ const db = new Database(config);
255
+
256
+ // TypeScript knows all methods and options!
257
+ await db.createResource({
258
+ name: 'users',
259
+ attributes: {
260
+ name: 'string|required',
261
+ email: 'string|required|email',
262
+ age: 'number|min:0'
263
+ }
264
+ });
265
+
266
+ // Full autocomplete for all operations
267
+ const users: Resource<any> = db.resources.users;
268
+ const user = await users.insert({ name: 'Alice', email: 'alice@example.com', age: 28 });
269
+ ```
270
+
271
+ ### Advanced: Generate Resource Types
272
+
273
+ For even better type safety, auto-generate TypeScript interfaces from your resources:
274
+
275
+ ```typescript
276
+ import { generateTypes } from 's3db.js/typescript-generator';
277
+
278
+ // Generate types after creating resources
279
+ await generateTypes(db, { outputPath: './types/database.d.ts' });
280
+ ```
281
+
282
+ This creates type-safe interfaces:
283
+
284
+ ```typescript
285
+ // types/database.d.ts (auto-generated)
286
+ export interface Users {
287
+ id: string;
288
+ name: string;
289
+ email: string;
290
+ age: number;
291
+ createdAt: string;
292
+ updatedAt: string;
293
+ }
294
+
295
+ export interface ResourceMap {
296
+ users: Resource<Users>;
297
+ posts: Resource<Posts>;
298
+ }
299
+
300
+ declare module 's3db.js' {
301
+ interface Database {
302
+ resources: ResourceMap;
303
+ }
304
+ }
305
+ ```
306
+
307
+ Now get full autocomplete for your specific fields:
308
+
309
+ ```typescript
310
+ import { Users } from './types/database';
311
+
312
+ const user = await db.resources.users.get('id');
313
+ // user is typed as Users - full autocomplete!
314
+
315
+ user.name // ✅ Autocomplete works
316
+ user.email // ✅ Autocomplete works
317
+ user.emai // ❌ Compile error - typo detected!
318
+ ```
319
+
320
+ ### Benefits
321
+
322
+ - ✅ **Full Type Safety** - Catch errors at compile time
323
+ - ✅ **IDE Autocomplete** - IntelliSense for all methods and properties
324
+ - ✅ **Refactoring Support** - Rename fields safely across your codebase
325
+ - ✅ **Documentation** - Hover tooltips show method signatures
326
+ - ✅ **Type Inference** - TypeScript infers return types automatically
327
+
328
+ See the complete example in [`docs/examples/typescript-usage-example.ts`](docs/examples/typescript-usage-example.ts).
329
+
189
330
  ---
190
331
 
191
332
  ## 💾 Installation
@@ -236,99 +377,15 @@ DATABASE_NAME=myapp
236
377
  Then initialize s3db.js:
237
378
 
238
379
  ```javascript
239
- import { S3db } from "s3db.js";
240
380
  import dotenv from "dotenv";
241
-
242
381
  dotenv.config();
243
382
 
383
+ import { S3db } from "s3db.js";
244
384
  const s3db = new S3db({
245
385
  connectionString: `s3://${process.env.AWS_ACCESS_KEY_ID}:${process.env.AWS_SECRET_ACCESS_KEY}@${process.env.AWS_BUCKET}/databases/${process.env.DATABASE_NAME}`
246
386
  });
247
387
  ```
248
388
 
249
- ### 🧪 Development & Testing
250
-
251
- For local development, all plugin dependencies are already included as **devDependencies** - just run:
252
-
253
- ```bash
254
- pnpm install # Installs everything including plugin dependencies
255
- ```
256
-
257
- This automatically installs all plugin dependencies so you can:
258
- - ✅ Run the full test suite (`pnpm test`)
259
- - ✅ Test all plugins without errors
260
- - ✅ Verify compatibility with all integrations
261
-
262
- **For end users:** They only install what they need via `peerDependencies`. The package manager automatically checks version compatibility.
263
-
264
- **For CI/CD:** Just `pnpm install` - no extra steps needed!
265
-
266
- ---
267
-
268
- ### ⚡ HTTP Client Configuration
269
-
270
- s3db.js includes optimized HTTP client settings by default for excellent S3 performance. You can customize these settings based on your specific needs:
271
-
272
- #### Default Configuration (Optimized)
273
-
274
- ```javascript
275
- const s3db = new S3db({
276
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
277
- // Default HTTP client options (optimized for most applications):
278
- httpClientOptions: {
279
- keepAlive: true, // Enable connection reuse
280
- keepAliveMsecs: 1000, // Keep connections alive for 1 second
281
- maxSockets: 50, // Maximum 50 concurrent connections
282
- maxFreeSockets: 10, // Keep 10 free connections in pool
283
- timeout: 60000 // 60 second timeout
284
- }
285
- });
286
- ```
287
-
288
- #### Custom Configurations
289
-
290
- **High Concurrency (Recommended for APIs):**
291
- ```javascript
292
- const s3db = new S3db({
293
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
294
- httpClientOptions: {
295
- keepAlive: true,
296
- keepAliveMsecs: 1000,
297
- maxSockets: 100, // Higher concurrency
298
- maxFreeSockets: 20, // More free connections
299
- timeout: 60000
300
- }
301
- });
302
- ```
303
-
304
- **Aggressive Performance (High-throughput applications):**
305
- ```javascript
306
- const s3db = new S3db({
307
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
308
- httpClientOptions: {
309
- keepAlive: true,
310
- keepAliveMsecs: 5000, // Longer keep-alive
311
- maxSockets: 200, // High concurrency
312
- maxFreeSockets: 50, // Large connection pool
313
- timeout: 120000 // 2 minute timeout
314
- }
315
- });
316
- ```
317
-
318
- **Conservative (Resource-constrained environments):**
319
- ```javascript
320
- const s3db = new S3db({
321
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
322
- httpClientOptions: {
323
- keepAlive: true,
324
- keepAliveMsecs: 500, // Shorter keep-alive
325
- maxSockets: 10, // Lower concurrency
326
- maxFreeSockets: 2, // Smaller pool
327
- timeout: 15000 // 15 second timeout
328
- }
329
- });
330
- ```
331
-
332
389
  ### Authentication Methods
333
390
 
334
391
  <details>
@@ -482,7 +539,7 @@ Use bulk operations for better performance with large datasets:
482
539
 
483
540
  ```javascript
484
541
  // ✅ Efficient bulk operations
485
- const users = await s3db.resource('users');
542
+ const users = s3db.resources.users;
486
543
 
487
544
  // Bulk insert - much faster than individual inserts
488
545
  const newUsers = await users.insertMany([
@@ -573,98 +630,6 @@ importData.forEach(userData => writableStream.write(userData));
573
630
  writableStream.end();
574
631
  ```
575
632
 
576
- ### 🔧 Troubleshooting
577
-
578
- #### HTTP Client Performance Issues
579
-
580
- If you're experiencing slow performance or connection issues:
581
-
582
- **1. Check your HTTP client configuration:**
583
- ```javascript
584
- // Verify current settings
585
- console.log('HTTP Client Options:', s3db.client.httpClientOptions);
586
- ```
587
-
588
- **2. Adjust for your use case:**
589
- ```javascript
590
- // For high-concurrency applications
591
- const s3db = new S3db({
592
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
593
- httpClientOptions: {
594
- keepAlive: true,
595
- maxSockets: 100, // Increase for more concurrency
596
- maxFreeSockets: 20, // More free connections
597
- timeout: 60000
598
- }
599
- });
600
-
601
- // For resource-constrained environments
602
- const s3db = new S3db({
603
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
604
- httpClientOptions: {
605
- keepAlive: true,
606
- maxSockets: 10, // Reduce for lower memory usage
607
- maxFreeSockets: 2, // Smaller pool
608
- timeout: 15000 // Shorter timeout
609
- }
610
- });
611
- ```
612
-
613
- **3. Use bulk operations for better performance:**
614
- ```javascript
615
- // ❌ Slow: Individual operations
616
- for (const item of items) {
617
- await users.insert(item);
618
- }
619
-
620
- // ✅ Fast: Bulk operations
621
- await users.insertMany(items);
622
- ```
623
-
624
- #### Best Practices for HTTP Configuration
625
-
626
- **For Web Applications:**
627
- ```javascript
628
- const s3db = new S3db({
629
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
630
- httpClientOptions: {
631
- keepAlive: true,
632
- keepAliveMsecs: 1000,
633
- maxSockets: 50, // Good balance for web traffic
634
- maxFreeSockets: 10,
635
- timeout: 60000
636
- }
637
- });
638
- ```
639
-
640
- **For Data Processing Pipelines:**
641
- ```javascript
642
- const s3db = new S3db({
643
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
644
- httpClientOptions: {
645
- keepAlive: true,
646
- keepAliveMsecs: 5000, // Longer keep-alive for batch processing
647
- maxSockets: 200, // High concurrency for bulk operations
648
- maxFreeSockets: 50,
649
- timeout: 120000 // Longer timeout for large operations
650
- }
651
- });
652
- ```
653
-
654
- **For Serverless Functions:**
655
- ```javascript
656
- const s3db = new S3db({
657
- connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
658
- httpClientOptions: {
659
- keepAlive: true,
660
- keepAliveMsecs: 500, // Shorter keep-alive for serverless
661
- maxSockets: 10, // Lower concurrency for resource constraints
662
- maxFreeSockets: 2,
663
- timeout: 15000 // Shorter timeout for serverless limits
664
- }
665
- });
666
- ```
667
-
668
633
  ### 🔄 Resource Versioning System
669
634
 
670
635
  Automatically manages schema evolution and data migration:
@@ -822,21 +787,6 @@ await users.insert({ name: "John", email: "john@example.com" });
822
787
  // ✅ Data cached, costs tracked, indexed for search, metrics recorded, replicated, and audited
823
788
  ```
824
789
 
825
- #### Available Plugins
826
-
827
- - **💾 [Cache Plugin](./docs/plugins/cache.md)** - Intelligent caching (memory/S3) for performance
828
- - **💰 [Costs Plugin](./docs/plugins/costs.md)** - Real-time AWS S3 cost tracking
829
- - **🔍 [FullText Plugin](./docs/plugins/fulltext.md)** - Advanced search with automatic indexing
830
- - **📊 [Metrics Plugin](./docs/plugins/metrics.md)** - Performance monitoring and analytics
831
- - **🔄 [Replicator Plugin](./docs/plugins/replicator.md)** - Multi-target replication (S3DB, SQS, BigQuery, PostgreSQL)
832
- - **📝 [Audit Plugin](./docs/plugins/audit.md)** - Comprehensive audit logging for compliance
833
- - **📬 [Queue Consumer Plugin](./docs/plugins/queue-consumer.md)** - Message consumption from SQS/RabbitMQ
834
- - **🔒 [S3Queue Plugin](./docs/plugins/s3-queue.md)** - Distributed queue processing with zero race conditions
835
- - **📈 [Eventual Consistency Plugin](./docs/plugins/eventual-consistency.md)** - Transactional counters with pre-computed analytics (15 functions for time-series data)
836
- - **📅 [Scheduler Plugin](./docs/plugins/scheduler.md)** - Task scheduling and automation
837
- - **🔄 [State Machine Plugin](./docs/plugins/state-machine.md)** - State management and transitions
838
- - **💾 [Backup Plugin](./docs/plugins/backup.md)** - Backup and restore functionality
839
-
840
790
  **📖 For complete plugin documentation and overview:**
841
791
  **[📋 Plugin Documentation Index](./docs/plugins/README.md)**
842
792
 
@@ -862,7 +812,7 @@ s3db.js uses a **lightweight core** approach - plugin-specific dependencies are
862
812
  | SQS Replicator | `@aws-sdk/client-sqs` | `^3.0.0` | `pnpm add @aws-sdk/client-sqs` |
863
813
  | SQS Consumer | `@aws-sdk/client-sqs` | `^3.0.0` | `pnpm add @aws-sdk/client-sqs` |
864
814
  | RabbitMQ Consumer | `amqplib` | `^0.10.0` | `pnpm add amqplib` |
865
- | Terraform State Plugin | `node-cron` | `^4.0.0` | `pnpm add node-cron` |
815
+ | Tfstate Plugin | `node-cron` | `^4.0.0` | `pnpm add node-cron` |
866
816
 
867
817
  **Example Error:**
868
818
 
@@ -2107,7 +2057,7 @@ await dbHealthCheck({ includeOrphanedPartitions: true })
2107
2057
  |--------|-------------|---------|
2108
2058
  | `connect()` | Connect to database | `await s3db.connect()` |
2109
2059
  | `createResource(config)` | Create new resource | `await s3db.createResource({...})` |
2110
- | `resource(name)` | Get resource reference | `const users = s3db.resource("users")` |
2060
+ | `resources.{name}` | Get resource reference | `const users = s3db.resources.users` |
2111
2061
  | `resourceExists(name)` | Check if resource exists | `s3db.resourceExists("users")` |
2112
2062
 
2113
2063
  ### ⚙️ Configuration Options
@@ -2260,4 +2210,70 @@ All benchmarks include:
2260
2210
  - ✅ **Performance metrics** - Real numbers with explanations
2261
2211
  - ✅ **Use cases** - When to apply each optimization
2262
2212
 
2263
- **[📋 Complete Benchmark Index](./docs/benchmarks/README.md)**
2213
+ **[📋 Complete Benchmark Index](./docs/benchmarks/README.md)**
2214
+
2215
+ ---
2216
+
2217
+ ## ⚡ HTTP Client Configuration
2218
+
2219
+ s3db.js includes optimized HTTP client settings by default for excellent S3 performance. You can customize these settings based on your specific needs:
2220
+
2221
+ ### Default Configuration (Optimized)
2222
+
2223
+ ```javascript
2224
+ const s3db = new S3db({
2225
+ connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
2226
+ // Default HTTP client options (optimized for most applications):
2227
+ httpClientOptions: {
2228
+ keepAlive: true, // Enable connection reuse
2229
+ keepAliveMsecs: 1000, // Keep connections alive for 1 second
2230
+ maxSockets: 50, // Maximum 50 concurrent connections
2231
+ maxFreeSockets: 10, // Keep 10 free connections in pool
2232
+ timeout: 60000 // 60 second timeout
2233
+ }
2234
+ });
2235
+ ```
2236
+
2237
+ ### Custom Configurations
2238
+
2239
+ **High Concurrency (Recommended for APIs):**
2240
+ ```javascript
2241
+ const s3db = new S3db({
2242
+ connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
2243
+ httpClientOptions: {
2244
+ keepAlive: true,
2245
+ keepAliveMsecs: 1000,
2246
+ maxSockets: 100, // Higher concurrency
2247
+ maxFreeSockets: 20, // More free connections
2248
+ timeout: 60000
2249
+ }
2250
+ });
2251
+ ```
2252
+
2253
+ **Aggressive Performance (High-throughput applications):**
2254
+ ```javascript
2255
+ const s3db = new S3db({
2256
+ connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
2257
+ httpClientOptions: {
2258
+ keepAlive: true,
2259
+ keepAliveMsecs: 5000, // Longer keep-alive
2260
+ maxSockets: 200, // High concurrency
2261
+ maxFreeSockets: 50, // Large connection pool
2262
+ timeout: 120000 // 2 minute timeout
2263
+ }
2264
+ });
2265
+ ```
2266
+
2267
+ **Conservative (Resource-constrained environments):**
2268
+ ```javascript
2269
+ const s3db = new S3db({
2270
+ connectionString: "s3://ACCESS_KEY:SECRET_KEY@BUCKET_NAME/databases/myapp",
2271
+ httpClientOptions: {
2272
+ keepAlive: true,
2273
+ keepAliveMsecs: 500, // Shorter keep-alive
2274
+ maxSockets: 10, // Lower concurrency
2275
+ maxFreeSockets: 2, // Smaller pool
2276
+ timeout: 15000 // 15 second timeout
2277
+ }
2278
+ });
2279
+ ```