@soulcraft/brainy 3.0.0 → 3.0.1

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 (260) hide show
  1. package/CHANGELOG.md +53 -3
  2. package/README.md +353 -110
  3. package/bin/brainy.js +340 -62
  4. package/dist/api/ConfigAPI.d.ts +67 -0
  5. package/dist/api/ConfigAPI.js +166 -0
  6. package/dist/api/DataAPI.d.ts +123 -0
  7. package/dist/api/DataAPI.js +391 -0
  8. package/dist/api/SecurityAPI.d.ts +50 -0
  9. package/dist/api/SecurityAPI.js +139 -0
  10. package/dist/api/UniversalImportAPI.d.ts +134 -0
  11. package/dist/api/UniversalImportAPI.js +615 -0
  12. package/dist/augmentationManager.js +12 -7
  13. package/dist/augmentationPipeline.d.ts +0 -61
  14. package/dist/augmentationPipeline.js +0 -87
  15. package/dist/augmentationRegistry.d.ts +1 -1
  16. package/dist/augmentationRegistry.js +1 -1
  17. package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
  18. package/dist/augmentations/apiServerAugmentation.js +290 -9
  19. package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
  20. package/dist/augmentations/auditLogAugmentation.js +358 -0
  21. package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
  22. package/dist/augmentations/batchProcessingAugmentation.js +123 -22
  23. package/dist/augmentations/brainyAugmentation.d.ts +142 -8
  24. package/dist/augmentations/brainyAugmentation.js +179 -2
  25. package/dist/augmentations/cacheAugmentation.d.ts +8 -5
  26. package/dist/augmentations/cacheAugmentation.js +116 -17
  27. package/dist/augmentations/conduitAugmentations.d.ts +2 -2
  28. package/dist/augmentations/conduitAugmentations.js +2 -2
  29. package/dist/augmentations/configResolver.d.ts +122 -0
  30. package/dist/augmentations/configResolver.js +440 -0
  31. package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
  32. package/dist/augmentations/connectionPoolAugmentation.js +37 -12
  33. package/dist/augmentations/defaultAugmentations.d.ts +14 -10
  34. package/dist/augmentations/defaultAugmentations.js +16 -11
  35. package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
  36. package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
  37. package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
  38. package/dist/augmentations/discovery/localDiscovery.js +246 -0
  39. package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
  40. package/dist/augmentations/discovery/runtimeLoader.js +337 -0
  41. package/dist/augmentations/discovery.d.ts +152 -0
  42. package/dist/augmentations/discovery.js +441 -0
  43. package/dist/augmentations/display/cache.d.ts +130 -0
  44. package/dist/augmentations/display/cache.js +319 -0
  45. package/dist/augmentations/display/fieldPatterns.d.ts +52 -0
  46. package/dist/augmentations/display/fieldPatterns.js +393 -0
  47. package/dist/augmentations/display/iconMappings.d.ts +57 -0
  48. package/dist/augmentations/display/iconMappings.js +68 -0
  49. package/dist/augmentations/display/intelligentComputation.d.ts +109 -0
  50. package/dist/augmentations/display/intelligentComputation.js +462 -0
  51. package/dist/augmentations/display/types.d.ts +203 -0
  52. package/dist/augmentations/display/types.js +7 -0
  53. package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
  54. package/dist/augmentations/entityRegistryAugmentation.js +5 -1
  55. package/dist/augmentations/indexAugmentation.d.ts +5 -3
  56. package/dist/augmentations/indexAugmentation.js +5 -2
  57. package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +24 -7
  58. package/dist/augmentations/intelligentVerbScoringAugmentation.js +111 -27
  59. package/dist/augmentations/manifest.d.ts +176 -0
  60. package/dist/augmentations/manifest.js +8 -0
  61. package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
  62. package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
  63. package/dist/augmentations/marketplace/cli.d.ts +47 -0
  64. package/dist/augmentations/marketplace/cli.js +265 -0
  65. package/dist/augmentations/metricsAugmentation.d.ts +3 -3
  66. package/dist/augmentations/metricsAugmentation.js +2 -2
  67. package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
  68. package/dist/augmentations/monitoringAugmentation.js +2 -2
  69. package/dist/augmentations/neuralImport.d.ts +1 -1
  70. package/dist/augmentations/neuralImport.js +4 -4
  71. package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
  72. package/dist/augmentations/rateLimitAugmentation.js +321 -0
  73. package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
  74. package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
  75. package/dist/augmentations/storageAugmentation.d.ts +1 -1
  76. package/dist/augmentations/storageAugmentation.js +2 -2
  77. package/dist/augmentations/storageAugmentations.d.ts +37 -8
  78. package/dist/augmentations/storageAugmentations.js +204 -15
  79. package/dist/augmentations/synapseAugmentation.d.ts +1 -1
  80. package/dist/augmentations/synapseAugmentation.js +35 -16
  81. package/dist/augmentations/typeMatching/brainyTypes.d.ts +83 -0
  82. package/dist/augmentations/typeMatching/brainyTypes.js +425 -0
  83. package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
  84. package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
  85. package/dist/augmentations/universalDisplayAugmentation.d.ts +191 -0
  86. package/dist/augmentations/universalDisplayAugmentation.js +371 -0
  87. package/dist/brainy-unified.d.ts +106 -0
  88. package/dist/brainy-unified.js +327 -0
  89. package/dist/brainy.d.ts +273 -0
  90. package/dist/brainy.js +1181 -0
  91. package/dist/brainyData.d.ts +56 -111
  92. package/dist/brainyData.js +912 -756
  93. package/dist/brainyDataV3.d.ts +186 -0
  94. package/dist/brainyDataV3.js +337 -0
  95. package/dist/browserFramework.d.ts +6 -6
  96. package/dist/browserFramework.js +11 -8
  97. package/dist/browserFramework.minimal.d.ts +5 -5
  98. package/dist/browserFramework.minimal.js +11 -8
  99. package/dist/config/distributedPresets-new.d.ts +118 -0
  100. package/dist/config/distributedPresets-new.js +318 -0
  101. package/dist/config/distributedPresets.d.ts +118 -0
  102. package/dist/config/distributedPresets.js +318 -0
  103. package/dist/config/extensibleConfig.d.ts +99 -0
  104. package/dist/config/extensibleConfig.js +268 -0
  105. package/dist/config/index.d.ts +17 -0
  106. package/dist/config/index.js +35 -0
  107. package/dist/config/modelAutoConfig.d.ts +32 -0
  108. package/dist/config/modelAutoConfig.js +139 -0
  109. package/dist/config/modelPrecisionManager.d.ts +42 -0
  110. package/dist/config/modelPrecisionManager.js +98 -0
  111. package/dist/config/sharedConfigManager.d.ts +67 -0
  112. package/dist/config/sharedConfigManager.js +215 -0
  113. package/dist/config/storageAutoConfig.d.ts +41 -0
  114. package/dist/config/storageAutoConfig.js +328 -0
  115. package/dist/config/zeroConfig.d.ts +68 -0
  116. package/dist/config/zeroConfig.js +301 -0
  117. package/dist/cortex/backupRestore.d.ts +2 -2
  118. package/dist/cortex/backupRestore.js +85 -27
  119. package/dist/cortex/healthCheck.d.ts +2 -2
  120. package/dist/cortex/neuralImport.d.ts +2 -2
  121. package/dist/cortex/neuralImport.js +18 -13
  122. package/dist/cortex/performanceMonitor.d.ts +2 -2
  123. package/dist/critical/model-guardian.d.ts +4 -0
  124. package/dist/critical/model-guardian.js +31 -11
  125. package/dist/demo.d.ts +4 -4
  126. package/dist/demo.js +7 -7
  127. package/dist/distributed/cacheSync.d.ts +112 -0
  128. package/dist/distributed/cacheSync.js +265 -0
  129. package/dist/distributed/coordinator.d.ts +193 -0
  130. package/dist/distributed/coordinator.js +548 -0
  131. package/dist/distributed/httpTransport.d.ts +120 -0
  132. package/dist/distributed/httpTransport.js +446 -0
  133. package/dist/distributed/index.d.ts +8 -0
  134. package/dist/distributed/index.js +5 -0
  135. package/dist/distributed/networkTransport.d.ts +132 -0
  136. package/dist/distributed/networkTransport.js +633 -0
  137. package/dist/distributed/queryPlanner.d.ts +104 -0
  138. package/dist/distributed/queryPlanner.js +327 -0
  139. package/dist/distributed/readWriteSeparation.d.ts +134 -0
  140. package/dist/distributed/readWriteSeparation.js +350 -0
  141. package/dist/distributed/shardManager.d.ts +114 -0
  142. package/dist/distributed/shardManager.js +357 -0
  143. package/dist/distributed/shardMigration.d.ts +110 -0
  144. package/dist/distributed/shardMigration.js +289 -0
  145. package/dist/distributed/storageDiscovery.d.ts +160 -0
  146. package/dist/distributed/storageDiscovery.js +551 -0
  147. package/dist/embeddings/CachedEmbeddings.d.ts +40 -0
  148. package/dist/embeddings/CachedEmbeddings.js +146 -0
  149. package/dist/embeddings/EmbeddingManager.d.ts +102 -0
  150. package/dist/embeddings/EmbeddingManager.js +291 -0
  151. package/dist/embeddings/SingletonModelManager.d.ts +95 -0
  152. package/dist/embeddings/SingletonModelManager.js +220 -0
  153. package/dist/embeddings/index.d.ts +12 -0
  154. package/dist/embeddings/index.js +16 -0
  155. package/dist/embeddings/lightweight-embedder.d.ts +0 -1
  156. package/dist/embeddings/lightweight-embedder.js +4 -12
  157. package/dist/embeddings/model-manager.d.ts +11 -0
  158. package/dist/embeddings/model-manager.js +43 -7
  159. package/dist/embeddings/universal-memory-manager.d.ts +1 -1
  160. package/dist/embeddings/universal-memory-manager.js +27 -67
  161. package/dist/embeddings/worker-embedding.js +4 -8
  162. package/dist/errors/brainyError.d.ts +5 -1
  163. package/dist/errors/brainyError.js +12 -0
  164. package/dist/examples/basicUsage.js +7 -4
  165. package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
  166. package/dist/graph/graphAdjacencyIndex.js +288 -0
  167. package/dist/graph/pathfinding.js +4 -2
  168. package/dist/hnsw/scaledHNSWSystem.js +11 -2
  169. package/dist/importManager.js +8 -5
  170. package/dist/index.d.ts +17 -22
  171. package/dist/index.js +37 -23
  172. package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
  173. package/dist/mcp/brainyMCPAdapter.js +5 -5
  174. package/dist/mcp/brainyMCPService.d.ts +3 -3
  175. package/dist/mcp/brainyMCPService.js +3 -11
  176. package/dist/mcp/mcpAugmentationToolset.js +20 -30
  177. package/dist/neural/embeddedPatterns.d.ts +1 -1
  178. package/dist/neural/embeddedPatterns.js +2 -2
  179. package/dist/neural/entityExtractor.d.ts +65 -0
  180. package/dist/neural/entityExtractor.js +316 -0
  181. package/dist/neural/improvedNeuralAPI.d.ts +357 -0
  182. package/dist/neural/improvedNeuralAPI.js +2628 -0
  183. package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
  184. package/dist/neural/naturalLanguageProcessor.js +941 -66
  185. package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
  186. package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
  187. package/dist/neural/neuralAPI.js +8 -2
  188. package/dist/neural/patternLibrary.d.ts +57 -3
  189. package/dist/neural/patternLibrary.js +348 -13
  190. package/dist/neural/staticPatternMatcher.d.ts +2 -2
  191. package/dist/neural/staticPatternMatcher.js +2 -2
  192. package/dist/neural/types.d.ts +287 -0
  193. package/dist/neural/types.js +24 -0
  194. package/dist/shared/default-augmentations.d.ts +3 -3
  195. package/dist/shared/default-augmentations.js +5 -5
  196. package/dist/storage/adapters/baseStorageAdapter.d.ts +42 -0
  197. package/dist/storage/adapters/fileSystemStorage.d.ts +26 -2
  198. package/dist/storage/adapters/fileSystemStorage.js +218 -15
  199. package/dist/storage/adapters/memoryStorage.d.ts +4 -4
  200. package/dist/storage/adapters/memoryStorage.js +17 -12
  201. package/dist/storage/adapters/opfsStorage.d.ts +2 -2
  202. package/dist/storage/adapters/opfsStorage.js +2 -2
  203. package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
  204. package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
  205. package/dist/storage/backwardCompatibility.d.ts +10 -78
  206. package/dist/storage/backwardCompatibility.js +17 -132
  207. package/dist/storage/baseStorage.d.ts +18 -2
  208. package/dist/storage/baseStorage.js +74 -3
  209. package/dist/storage/cacheManager.js +2 -2
  210. package/dist/storage/readOnlyOptimizations.js +8 -3
  211. package/dist/streaming/pipeline.d.ts +154 -0
  212. package/dist/streaming/pipeline.js +551 -0
  213. package/dist/triple/TripleIntelligence.d.ts +25 -110
  214. package/dist/triple/TripleIntelligence.js +4 -574
  215. package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
  216. package/dist/triple/TripleIntelligenceSystem.js +519 -0
  217. package/dist/types/apiTypes.d.ts +278 -0
  218. package/dist/types/apiTypes.js +33 -0
  219. package/dist/types/brainy.types.d.ts +308 -0
  220. package/dist/types/brainy.types.js +8 -0
  221. package/dist/types/brainyDataInterface.d.ts +5 -8
  222. package/dist/types/brainyDataInterface.js +2 -2
  223. package/dist/types/graphTypes.js +2 -2
  224. package/dist/utils/brainyTypes.d.ts +217 -0
  225. package/dist/utils/brainyTypes.js +261 -0
  226. package/dist/utils/cacheAutoConfig.d.ts +3 -3
  227. package/dist/utils/embedding.d.ts +9 -4
  228. package/dist/utils/embedding.js +89 -26
  229. package/dist/utils/enhancedLogger.d.ts +104 -0
  230. package/dist/utils/enhancedLogger.js +232 -0
  231. package/dist/utils/hybridModelManager.d.ts +19 -28
  232. package/dist/utils/hybridModelManager.js +36 -200
  233. package/dist/utils/index.d.ts +1 -1
  234. package/dist/utils/index.js +1 -1
  235. package/dist/utils/intelligentTypeMapper.d.ts +60 -0
  236. package/dist/utils/intelligentTypeMapper.js +349 -0
  237. package/dist/utils/metadataIndex.d.ts +118 -1
  238. package/dist/utils/metadataIndex.js +539 -16
  239. package/dist/utils/nodeVersionCheck.d.ts +24 -0
  240. package/dist/utils/nodeVersionCheck.js +65 -0
  241. package/dist/utils/paramValidation.d.ts +39 -0
  242. package/dist/utils/paramValidation.js +192 -0
  243. package/dist/utils/rateLimiter.d.ts +160 -0
  244. package/dist/utils/rateLimiter.js +271 -0
  245. package/dist/utils/statistics.d.ts +4 -4
  246. package/dist/utils/statistics.js +3 -3
  247. package/dist/utils/structuredLogger.d.ts +146 -0
  248. package/dist/utils/structuredLogger.js +394 -0
  249. package/dist/utils/textEncoding.js +2 -1
  250. package/dist/utils/typeValidation.d.ts +59 -0
  251. package/dist/utils/typeValidation.js +374 -0
  252. package/dist/utils/version.js +19 -3
  253. package/package.json +15 -4
  254. package/scripts/download-models.cjs +94 -20
  255. package/dist/augmentations/walAugmentation.d.ts +0 -109
  256. package/dist/augmentations/walAugmentation.js +0 -516
  257. package/dist/chat/BrainyChat.d.ts +0 -121
  258. package/dist/chat/BrainyChat.js +0 -396
  259. package/dist/chat/ChatCLI.d.ts +0 -61
  260. package/dist/chat/ChatCLI.js +0 -351
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Rate Limiter for Brainy API
3
+ *
4
+ * Provides rate limiting without external dependencies like Redis.
5
+ * - Uses in-memory storage for single instances
6
+ * - Can use S3/R2 for distributed rate limiting
7
+ *
8
+ * @module rateLimiter
9
+ */
10
+ /**
11
+ * Simple in-memory rate limiter
12
+ */
13
+ export class RateLimiter {
14
+ constructor(config) {
15
+ this.config = config;
16
+ this.requests = new Map();
17
+ this.cleanupInterval = null;
18
+ // Start cleanup interval to remove expired entries
19
+ this.startCleanup();
20
+ }
21
+ /**
22
+ * Check if a request is allowed and update the rate limit
23
+ */
24
+ async checkLimit(identifier) {
25
+ const now = Date.now();
26
+ if (this.config.distributed && this.config.storage) {
27
+ return this.checkDistributedLimit(identifier, now);
28
+ }
29
+ return this.checkMemoryLimit(identifier, now);
30
+ }
31
+ /**
32
+ * Check rate limit using in-memory storage
33
+ */
34
+ checkMemoryLimit(identifier, now) {
35
+ const entry = this.requests.get(identifier);
36
+ const resetTime = now + this.config.windowMs;
37
+ if (!entry || entry.resetTime <= now) {
38
+ // New window or expired window
39
+ this.requests.set(identifier, {
40
+ count: 1,
41
+ resetTime
42
+ });
43
+ return {
44
+ allowed: true,
45
+ remaining: this.config.maxRequests - 1,
46
+ resetTime,
47
+ limit: this.config.maxRequests
48
+ };
49
+ }
50
+ // Existing window
51
+ if (entry.count < this.config.maxRequests) {
52
+ entry.count++;
53
+ return {
54
+ allowed: true,
55
+ remaining: this.config.maxRequests - entry.count,
56
+ resetTime: entry.resetTime,
57
+ limit: this.config.maxRequests
58
+ };
59
+ }
60
+ // Rate limit exceeded
61
+ return {
62
+ allowed: false,
63
+ remaining: 0,
64
+ resetTime: entry.resetTime,
65
+ limit: this.config.maxRequests
66
+ };
67
+ }
68
+ /**
69
+ * Check rate limit using distributed storage (S3/R2)
70
+ */
71
+ async checkDistributedLimit(identifier, now) {
72
+ const storage = this.config.storage;
73
+ const key = `ratelimit_${identifier}`;
74
+ const resetTime = now + this.config.windowMs;
75
+ try {
76
+ // Try to get existing rate limit data from metadata storage
77
+ const existing = await storage.getMetadata(key);
78
+ if (!existing || !existing.resetTime ||
79
+ Number(existing.resetTime) <= now) {
80
+ // New window or expired window
81
+ await storage.saveMetadata(key, {
82
+ count: 1,
83
+ resetTime: resetTime,
84
+ identifier
85
+ });
86
+ return {
87
+ allowed: true,
88
+ remaining: this.config.maxRequests - 1,
89
+ resetTime,
90
+ limit: this.config.maxRequests
91
+ };
92
+ }
93
+ const count = Number(existing.count || 0);
94
+ if (count < this.config.maxRequests) {
95
+ // Update count
96
+ await storage.saveMetadata(key, {
97
+ count: count + 1,
98
+ resetTime: existing.resetTime,
99
+ identifier
100
+ });
101
+ return {
102
+ allowed: true,
103
+ remaining: this.config.maxRequests - count - 1,
104
+ resetTime: Number(existing.resetTime),
105
+ limit: this.config.maxRequests
106
+ };
107
+ }
108
+ // Rate limit exceeded
109
+ return {
110
+ allowed: false,
111
+ remaining: 0,
112
+ resetTime: Number(existing.resetTime),
113
+ limit: this.config.maxRequests
114
+ };
115
+ }
116
+ catch (error) {
117
+ // On error, fail open (allow the request)
118
+ console.warn('Rate limiter error, failing open:', error);
119
+ return {
120
+ allowed: true,
121
+ remaining: this.config.maxRequests,
122
+ resetTime,
123
+ limit: this.config.maxRequests
124
+ };
125
+ }
126
+ }
127
+ /**
128
+ * Reset rate limit for a specific identifier
129
+ */
130
+ async reset(identifier) {
131
+ if (this.config.distributed && this.config.storage) {
132
+ const key = `ratelimit_${identifier}`;
133
+ // Reset by setting count to 0 and expired time
134
+ await this.config.storage.saveMetadata(key, {
135
+ count: 0,
136
+ resetTime: 0,
137
+ identifier
138
+ });
139
+ }
140
+ else {
141
+ this.requests.delete(identifier);
142
+ }
143
+ }
144
+ /**
145
+ * Start cleanup interval to remove expired entries
146
+ */
147
+ startCleanup() {
148
+ // Run cleanup every minute
149
+ this.cleanupInterval = setInterval(() => {
150
+ const now = Date.now();
151
+ const expired = [];
152
+ for (const [key, entry] of this.requests) {
153
+ if (entry.resetTime <= now) {
154
+ expired.push(key);
155
+ }
156
+ }
157
+ for (const key of expired) {
158
+ this.requests.delete(key);
159
+ }
160
+ }, 60000); // 1 minute
161
+ // Don't keep Node.js process alive just for cleanup
162
+ if (this.cleanupInterval.unref) {
163
+ this.cleanupInterval.unref();
164
+ }
165
+ }
166
+ /**
167
+ * Stop the rate limiter and cleanup
168
+ */
169
+ destroy() {
170
+ if (this.cleanupInterval) {
171
+ clearInterval(this.cleanupInterval);
172
+ this.cleanupInterval = null;
173
+ }
174
+ this.requests.clear();
175
+ }
176
+ }
177
+ /**
178
+ * Express/Connect middleware for rate limiting
179
+ */
180
+ export function rateLimitMiddleware(config) {
181
+ const limiter = new RateLimiter(config);
182
+ return async (req, res, next) => {
183
+ // Use IP address as identifier (can be customized)
184
+ const identifier = req.ip || req.connection?.remoteAddress || 'unknown';
185
+ const result = await limiter.checkLimit(identifier);
186
+ // Set rate limit headers
187
+ res.setHeader('X-RateLimit-Limit', result.limit);
188
+ res.setHeader('X-RateLimit-Remaining', result.remaining);
189
+ res.setHeader('X-RateLimit-Reset', result.resetTime);
190
+ if (!result.allowed) {
191
+ res.status(429).json({
192
+ error: config.message || 'Too many requests, please try again later.',
193
+ retryAfter: Math.ceil((result.resetTime - Date.now()) / 1000)
194
+ });
195
+ return;
196
+ }
197
+ next();
198
+ };
199
+ }
200
+ /**
201
+ * Create a rate limiter for use with Brainy
202
+ *
203
+ * @example
204
+ * ```typescript
205
+ * // For single instance (in-memory)
206
+ * const limiter = createRateLimiter({
207
+ * maxRequests: 100,
208
+ * windowMs: 15 * 60 * 1000 // 15 minutes
209
+ * })
210
+ *
211
+ * // For distributed (using S3/R2)
212
+ * const limiter = createRateLimiter({
213
+ * maxRequests: 100,
214
+ * windowMs: 15 * 60 * 1000,
215
+ * distributed: true,
216
+ * storage: myS3Adapter
217
+ * })
218
+ *
219
+ * // Check rate limit
220
+ * const result = await limiter.checkLimit('user-123')
221
+ * if (!result.allowed) {
222
+ * throw new Error('Rate limit exceeded')
223
+ * }
224
+ * ```
225
+ */
226
+ export function createRateLimiter(config) {
227
+ return new RateLimiter(config);
228
+ }
229
+ /**
230
+ * Preset configurations for common use cases
231
+ */
232
+ export const RateLimitPresets = {
233
+ /**
234
+ * Default API rate limit: 100 requests per 15 minutes
235
+ */
236
+ default: {
237
+ maxRequests: 100,
238
+ windowMs: 15 * 60 * 1000
239
+ },
240
+ /**
241
+ * Strict rate limit: 10 requests per minute
242
+ */
243
+ strict: {
244
+ maxRequests: 10,
245
+ windowMs: 60 * 1000
246
+ },
247
+ /**
248
+ * Lenient rate limit: 1000 requests per hour
249
+ */
250
+ lenient: {
251
+ maxRequests: 1000,
252
+ windowMs: 60 * 60 * 1000
253
+ },
254
+ /**
255
+ * Search endpoint: 30 requests per minute
256
+ */
257
+ search: {
258
+ maxRequests: 30,
259
+ windowMs: 60 * 1000,
260
+ message: 'Search rate limit exceeded. Please wait before searching again.'
261
+ },
262
+ /**
263
+ * Write operations: 20 requests per minute
264
+ */
265
+ write: {
266
+ maxRequests: 20,
267
+ windowMs: 60 * 1000,
268
+ message: 'Write rate limit exceeded. Please slow down your write operations.'
269
+ }
270
+ };
271
+ //# sourceMappingURL=rateLimiter.js.map
@@ -1,17 +1,17 @@
1
1
  /**
2
2
  * Utility functions for retrieving statistics from Brainy
3
3
  */
4
- import { BrainyData } from '../brainyData.js';
4
+ import { Brainy } from '../brainy.js';
5
5
  /**
6
- * Get statistics about the current state of a BrainyData instance
6
+ * Get statistics about the current state of a Brainy instance
7
7
  * This function provides access to statistics at the root level of the library
8
8
  *
9
- * @param instance A BrainyData instance to get statistics from
9
+ * @param instance A Brainy instance to get statistics from
10
10
  * @param options Additional options for retrieving statistics
11
11
  * @returns Object containing counts of nouns, verbs, metadata entries, and HNSW index size
12
12
  * @throws Error if the instance is not provided or if statistics retrieval fails
13
13
  */
14
- export declare function getStatistics(instance: BrainyData, options?: {
14
+ export declare function getStatistics(instance: Brainy, options?: {
15
15
  service?: string | string[];
16
16
  }): Promise<{
17
17
  nounCount: number;
@@ -2,17 +2,17 @@
2
2
  * Utility functions for retrieving statistics from Brainy
3
3
  */
4
4
  /**
5
- * Get statistics about the current state of a BrainyData instance
5
+ * Get statistics about the current state of a Brainy instance
6
6
  * This function provides access to statistics at the root level of the library
7
7
  *
8
- * @param instance A BrainyData instance to get statistics from
8
+ * @param instance A Brainy instance to get statistics from
9
9
  * @param options Additional options for retrieving statistics
10
10
  * @returns Object containing counts of nouns, verbs, metadata entries, and HNSW index size
11
11
  * @throws Error if the instance is not provided or if statistics retrieval fails
12
12
  */
13
13
  export async function getStatistics(instance, options = {}) {
14
14
  if (!instance) {
15
- throw new Error('BrainyData instance must be provided to getStatistics');
15
+ throw new Error('Brainy instance must be provided to getStatistics');
16
16
  }
17
17
  try {
18
18
  return await instance.getStatistics(options);
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Enhanced Structured Logging System for Brainy
3
+ * Provides production-ready logging with structured output, context preservation,
4
+ * performance tracking, and multiple transport support
5
+ */
6
+ export declare enum LogLevel {
7
+ SILENT = -1,
8
+ FATAL = 0,
9
+ ERROR = 1,
10
+ WARN = 2,
11
+ INFO = 3,
12
+ DEBUG = 4,
13
+ TRACE = 5
14
+ }
15
+ export interface LogContext {
16
+ requestId?: string;
17
+ userId?: string;
18
+ operation?: string;
19
+ entityId?: string;
20
+ entityType?: string;
21
+ [key: string]: any;
22
+ }
23
+ export interface LogEntry {
24
+ timestamp: string;
25
+ level: string;
26
+ levelNumeric: number;
27
+ module: string;
28
+ message: string;
29
+ context?: LogContext;
30
+ data?: any;
31
+ error?: {
32
+ name: string;
33
+ message: string;
34
+ stack?: string;
35
+ code?: string;
36
+ };
37
+ performance?: {
38
+ duration?: number;
39
+ memory?: {
40
+ used: number;
41
+ total: number;
42
+ };
43
+ };
44
+ host?: string;
45
+ pid: number;
46
+ version?: string;
47
+ }
48
+ export interface LogTransport {
49
+ name: string;
50
+ log(entry: LogEntry): void | Promise<void>;
51
+ flush?(): Promise<void>;
52
+ }
53
+ export interface StructuredLoggerConfig {
54
+ level: LogLevel;
55
+ modules?: Record<string, LogLevel>;
56
+ format: 'json' | 'pretty' | 'simple';
57
+ transports: LogTransport[];
58
+ context?: LogContext;
59
+ includeHost?: boolean;
60
+ includeMemory?: boolean;
61
+ bufferSize?: number;
62
+ flushInterval?: number;
63
+ version?: string;
64
+ }
65
+ export declare class StructuredLogger {
66
+ private static instance;
67
+ private config;
68
+ private defaultContext;
69
+ private performanceMarks;
70
+ private constructor();
71
+ private loadEnvironmentConfig;
72
+ static getInstance(): StructuredLogger;
73
+ configure(config: Partial<StructuredLoggerConfig>): void;
74
+ setContext(context: LogContext): void;
75
+ clearContext(): void;
76
+ withContext(context: LogContext): StructuredLogger;
77
+ startTimer(label: string): void;
78
+ endTimer(label: string): number | undefined;
79
+ private shouldLog;
80
+ private createLogEntry;
81
+ private log;
82
+ fatal(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
83
+ error(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
84
+ warn(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
85
+ info(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
86
+ debug(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
87
+ trace(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
88
+ createModuleLogger(module: string): {
89
+ fatal: (message: string, contextOrData?: LogContext | any, data?: any) => void;
90
+ error: (message: string, contextOrData?: LogContext | any, data?: any) => void;
91
+ warn: (message: string, contextOrData?: LogContext | any, data?: any) => void;
92
+ info: (message: string, contextOrData?: LogContext | any, data?: any) => void;
93
+ debug: (message: string, contextOrData?: LogContext | any, data?: any) => void;
94
+ trace: (message: string, contextOrData?: LogContext | any, data?: any) => void;
95
+ withContext: (context: LogContext) => {
96
+ fatal: (message: string, contextOrData?: LogContext | any, data?: any) => void;
97
+ error: (message: string, contextOrData?: LogContext | any, data?: any) => void;
98
+ warn: (message: string, contextOrData?: LogContext | any, data?: any) => void;
99
+ info: (message: string, contextOrData?: LogContext | any, data?: any) => void;
100
+ debug: (message: string, contextOrData?: LogContext | any, data?: any) => void;
101
+ trace: (message: string, contextOrData?: LogContext | any, data?: any) => void;
102
+ withContext: (context: LogContext) => /*elided*/ any;
103
+ startTimer: (label: string) => void;
104
+ endTimer: (label: string) => number | undefined;
105
+ };
106
+ startTimer: (label: string) => void;
107
+ endTimer: (label: string) => number | undefined;
108
+ };
109
+ flush(): Promise<void>;
110
+ addTransport(transport: LogTransport): void;
111
+ removeTransport(name: string): void;
112
+ child(context: LogContext): StructuredLogger;
113
+ }
114
+ export declare const structuredLogger: StructuredLogger;
115
+ export declare function createModuleLogger(module: string): {
116
+ fatal: (message: string, contextOrData?: LogContext | any, data?: any) => void;
117
+ error: (message: string, contextOrData?: LogContext | any, data?: any) => void;
118
+ warn: (message: string, contextOrData?: LogContext | any, data?: any) => void;
119
+ info: (message: string, contextOrData?: LogContext | any, data?: any) => void;
120
+ debug: (message: string, contextOrData?: LogContext | any, data?: any) => void;
121
+ trace: (message: string, contextOrData?: LogContext | any, data?: any) => void;
122
+ withContext: (context: LogContext) => /*elided*/ any;
123
+ startTimer: (label: string) => void;
124
+ endTimer: (label: string) => number | undefined;
125
+ };
126
+ export declare function setLogContext(context: LogContext): void;
127
+ export declare function withLogContext(context: LogContext): StructuredLogger;
128
+ export declare function createCorrelationId(): string;
129
+ export declare function logPerformance(logger: ReturnType<typeof createModuleLogger>, operation: string, fn: () => any): any;
130
+ export declare class LoggerCompatibilityWrapper {
131
+ private moduleLogger;
132
+ constructor(module?: string);
133
+ error(module: string, message: string, ...args: any[]): void;
134
+ warn(module: string, message: string, ...args: any[]): void;
135
+ info(module: string, message: string, ...args: any[]): void;
136
+ debug(module: string, message: string, ...args: any[]): void;
137
+ trace(module: string, message: string, ...args: any[]): void;
138
+ createModuleLogger(module: string): {
139
+ error: (message: string, ...args: any[]) => void;
140
+ warn: (message: string, ...args: any[]) => void;
141
+ info: (message: string, ...args: any[]) => void;
142
+ debug: (message: string, ...args: any[]) => void;
143
+ trace: (message: string, ...args: any[]) => void;
144
+ };
145
+ }
146
+ export type ModuleLogger = ReturnType<typeof createModuleLogger>;