@wishknish/knishio-client-ts 0.7.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 (141) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +425 -0
  3. package/dist/index.cjs +9961 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.iife.js +32241 -0
  6. package/dist/index.iife.js.map +1 -0
  7. package/dist/index.js +9853 -0
  8. package/dist/index.js.map +1 -0
  9. package/package.json +113 -0
  10. package/src/AuthToken.ts +214 -0
  11. package/src/KnishIOClient.ts +2020 -0
  12. package/src/constants.ts +398 -0
  13. package/src/core/Atom.ts +646 -0
  14. package/src/core/AtomMeta.ts +278 -0
  15. package/src/core/Meta.ts +428 -0
  16. package/src/core/Molecule.ts +825 -0
  17. package/src/core/PolicyMeta.ts +130 -0
  18. package/src/core/TokenUnit.ts +148 -0
  19. package/src/core/Wallet.ts +467 -0
  20. package/src/exception/AtomIndexException.ts +97 -0
  21. package/src/exception/AtomsMissingException.ts +109 -0
  22. package/src/exception/AuthorizationRejectedException.ts +63 -0
  23. package/src/exception/BalanceInsufficientException.ts +58 -0
  24. package/src/exception/BaseException.ts +275 -0
  25. package/src/exception/BatchIdException.ts +58 -0
  26. package/src/exception/CodeException.ts +119 -0
  27. package/src/exception/DecryptionKeyException.ts +65 -0
  28. package/src/exception/InvalidResponseException.ts +112 -0
  29. package/src/exception/MetaMissingException.ts +58 -0
  30. package/src/exception/MolecularHashMismatchException.ts +115 -0
  31. package/src/exception/MolecularHashMissingException.ts +58 -0
  32. package/src/exception/NegativeAmountException.ts +58 -0
  33. package/src/exception/PolicyInvalidException.ts +58 -0
  34. package/src/exception/SignatureMalformedException.ts +58 -0
  35. package/src/exception/SignatureMismatchException.ts +98 -0
  36. package/src/exception/StackableUnitAmountException.ts +65 -0
  37. package/src/exception/StackableUnitDecimalsException.ts +65 -0
  38. package/src/exception/TransferBalanceException.ts +98 -0
  39. package/src/exception/TransferMalformedException.ts +58 -0
  40. package/src/exception/TransferMismatchedException.ts +58 -0
  41. package/src/exception/TransferRemainderException.ts +58 -0
  42. package/src/exception/TransferToSelfException.ts +58 -0
  43. package/src/exception/TransferUnbalancedException.ts +58 -0
  44. package/src/exception/UnauthenticatedException.ts +147 -0
  45. package/src/exception/WalletCredentialException.ts +108 -0
  46. package/src/exception/WalletShadowException.ts +65 -0
  47. package/src/exception/WrongTokenTypeException.ts +58 -0
  48. package/src/exception/index.ts +272 -0
  49. package/src/index.ts +512 -0
  50. package/src/instance/rules/Callback.ts +257 -0
  51. package/src/instance/rules/Condition.ts +96 -0
  52. package/src/instance/rules/Meta.ts +163 -0
  53. package/src/instance/rules/Rule.ts +29 -0
  54. package/src/instance/rules/exception/RuleArgumentException.ts +65 -0
  55. package/src/libraries/CheckMolecule.ts +581 -0
  56. package/src/libraries/Decimal.ts +94 -0
  57. package/src/libraries/Dot.ts +202 -0
  58. package/src/libraries/GraphQLClient.ts +276 -0
  59. package/src/libraries/Hex.ts +155 -0
  60. package/src/libraries/UrqlClientWrapper.ts +336 -0
  61. package/src/libraries/array.ts +91 -0
  62. package/src/libraries/crypto.ts +816 -0
  63. package/src/libraries/strings.ts +458 -0
  64. package/src/mutation/Mutation.ts +103 -0
  65. package/src/mutation/MutationActiveSession.ts +108 -0
  66. package/src/mutation/MutationClaimShadowWallet.ts +91 -0
  67. package/src/mutation/MutationCreateIdentifier.ts +86 -0
  68. package/src/mutation/MutationCreateMeta.ts +92 -0
  69. package/src/mutation/MutationCreateRule.ts +90 -0
  70. package/src/mutation/MutationCreateToken.ts +92 -0
  71. package/src/mutation/MutationCreateWallet.ts +78 -0
  72. package/src/mutation/MutationDepositBufferToken.ts +72 -0
  73. package/src/mutation/MutationLinkIdentifier.ts +87 -0
  74. package/src/mutation/MutationProposeMolecule.ts +147 -0
  75. package/src/mutation/MutationRequestAuthorization.ts +77 -0
  76. package/src/mutation/MutationRequestAuthorizationGuest.ts +85 -0
  77. package/src/mutation/MutationRequestTokens.ts +98 -0
  78. package/src/mutation/MutationTransferTokens.ts +87 -0
  79. package/src/mutation/MutationWithdrawBufferToken.ts +73 -0
  80. package/src/query/Query.ts +187 -0
  81. package/src/query/QueryActiveSession.ts +89 -0
  82. package/src/query/QueryAtom.ts +275 -0
  83. package/src/query/QueryBalance.ts +102 -0
  84. package/src/query/QueryBatch.ts +145 -0
  85. package/src/query/QueryBatchHistory.ts +86 -0
  86. package/src/query/QueryContinuId.ts +91 -0
  87. package/src/query/QueryMetaType.ts +177 -0
  88. package/src/query/QueryMetaTypeViaAtom.ts +199 -0
  89. package/src/query/QueryPolicy.ts +91 -0
  90. package/src/query/QueryToken.ts +90 -0
  91. package/src/query/QueryUserActivity.ts +153 -0
  92. package/src/query/QueryWalletBundle.ts +92 -0
  93. package/src/query/QueryWalletList.ts +106 -0
  94. package/src/response/EnhancedResponse.ts +345 -0
  95. package/src/response/Response.ts +254 -0
  96. package/src/response/ResponseActiveSession.ts +72 -0
  97. package/src/response/ResponseAtom.ts +132 -0
  98. package/src/response/ResponseAuthorizationGuest.ts +119 -0
  99. package/src/response/ResponseBalance.ts +153 -0
  100. package/src/response/ResponseClaimShadowWallet.ts +56 -0
  101. package/src/response/ResponseContinuId.ts +101 -0
  102. package/src/response/ResponseCreateIdentifier.ts +56 -0
  103. package/src/response/ResponseCreateMeta.ts +58 -0
  104. package/src/response/ResponseCreateRule.ts +56 -0
  105. package/src/response/ResponseCreateToken.ts +58 -0
  106. package/src/response/ResponseCreateWallet.ts +58 -0
  107. package/src/response/ResponseLinkIdentifier.ts +87 -0
  108. package/src/response/ResponseMetaBatch.ts +72 -0
  109. package/src/response/ResponseMetaType.ts +108 -0
  110. package/src/response/ResponseMetaTypeViaAtom.ts +108 -0
  111. package/src/response/ResponsePolicy.ts +90 -0
  112. package/src/response/ResponseProposeMolecule.ts +155 -0
  113. package/src/response/ResponseQueryActiveSession.ts +105 -0
  114. package/src/response/ResponseQueryUserActivity.ts +89 -0
  115. package/src/response/ResponseRequestAuthorization.ts +100 -0
  116. package/src/response/ResponseRequestAuthorizationGuest.ts +133 -0
  117. package/src/response/ResponseRequestTokens.ts +58 -0
  118. package/src/response/ResponseTransferTokens.ts +72 -0
  119. package/src/response/ResponseWalletBundle.ts +95 -0
  120. package/src/response/ResponseWalletList.ts +165 -0
  121. package/src/schemas/index.ts +457 -0
  122. package/src/subscribe/ActiveSessionSubscribe.ts +72 -0
  123. package/src/subscribe/ActiveWalletSubscribe.ts +99 -0
  124. package/src/subscribe/CreateMoleculeSubscribe.ts +106 -0
  125. package/src/subscribe/Subscribe.ts +182 -0
  126. package/src/subscribe/WalletStatusSubscribe.ts +70 -0
  127. package/src/subscribe/index.ts +59 -0
  128. package/src/types/assertions.ts +722 -0
  129. package/src/types/client.ts +567 -0
  130. package/src/types/crypto.ts +541 -0
  131. package/src/types/graphql.ts +630 -0
  132. package/src/types/guards.ts +659 -0
  133. package/src/types/index.ts +614 -0
  134. package/src/types/response.ts +133 -0
  135. package/src/types/template-literals.ts +382 -0
  136. package/src/validation/UNIVERSAL_CONFIGURATION_INTERFACES.ts +580 -0
  137. package/src/validation/ValidationService.ts +607 -0
  138. package/src/validation/schemas.ts +447 -0
  139. package/src/versions/HashAtom.ts +170 -0
  140. package/src/versions/Version4.ts +120 -0
  141. package/src/versions/index.ts +80 -0
@@ -0,0 +1,580 @@
1
+ /*
2
+ (
3
+ (/(
4
+ (//(
5
+ (///(
6
+ (/////(
7
+ (//////( )
8
+ (////////( (/)
9
+ (////////( (///)
10
+ (//////////( (////)
11
+ (//////////( (//////)
12
+ (////////////( (///////)
13
+ (/////////////( (/////////)
14
+ (//////////////( (///////////)
15
+ (///////////////( (/////////////)
16
+ (////////////////( (//////////////)
17
+ ((((((((((((((((((( (((((((((((((((
18
+ ((((((((((((((((((( ((((((((((((((
19
+ ((((((((((((((((((( ((((((((((((((
20
+ (((((((((((((((((((( (((((((((((((
21
+ (((((((((((((((((((( ((((((((((((
22
+ ((((((((((((((((((( ((((((((((((
23
+ ((((((((((((((((((( ((((((((((
24
+ ((((((((((((((((((/ (((((((((
25
+ (((((((((((((((((( ((((((((
26
+ ((((((((((((((((( (((((((
27
+ (((((((((((((((((( (((((
28
+ ################# ##
29
+ ################ #
30
+ ################# ##
31
+ %################ ###
32
+ ###############( ####
33
+ ############### ####
34
+ ############### ######
35
+ %#############( (#######
36
+ %############# #########
37
+ ############( ##########
38
+ ########### #############
39
+ ######### ##############
40
+ %######
41
+
42
+ Powered by Knish.IO: Connecting a Decentralized World
43
+
44
+ Please visit https://github.com/WishKnish/KnishIO-Client-TS for information.
45
+
46
+ License: https://github.com/WishKnish/KnishIO-Client-TS/blob/master/LICENSE
47
+ */
48
+
49
+ /**
50
+ * UNIVERSAL_CONFIGURATION_INTERFACES.ts
51
+ *
52
+ * Enhanced configuration interfaces compatible with Phase 2 standardization
53
+ * across all KnishIO SDKs. Provides type-safe configuration validation with
54
+ * enhanced error handling and warning system integration.
55
+ *
56
+ * Features:
57
+ * - Universal configuration schemas across all SDKs
58
+ * - Enhanced validation with warnings and recommendations
59
+ * - Environment variable integration
60
+ * - Configuration migration support
61
+ * - Performance optimization hints
62
+ */
63
+
64
+ import { z } from 'zod'
65
+ import type { ValidationResult } from './ValidationService'
66
+
67
+ // =============================================================================
68
+ // UNIVERSAL CONFIGURATION TYPES
69
+ // =============================================================================
70
+
71
+ /**
72
+ * Enhanced client configuration interface with Phase 2 improvements
73
+ */
74
+ export interface UniversalClientConfig {
75
+ // Core connection settings
76
+ uri: string | string[]
77
+ cellSlug?: string | null
78
+
79
+ // Network configuration
80
+ timeout?: number
81
+ retries?: number
82
+ retryDelay?: number
83
+
84
+ // Security settings
85
+ encryption?: boolean
86
+ authToken?: string | null
87
+
88
+ // Performance tuning
89
+ connectionPoolSize?: number
90
+ keepAlive?: boolean
91
+ compression?: boolean
92
+
93
+ // SDK behavior
94
+ logging?: boolean
95
+ serverSdkVersion?: number
96
+ strictMode?: boolean
97
+
98
+ // Advanced features
99
+ socket?: {
100
+ socketUri: string | null
101
+ appKey?: string
102
+ } | null
103
+ client?: any | null
104
+
105
+ // Environment integration
106
+ environment?: 'development' | 'testing' | 'staging' | 'production'
107
+
108
+ // Migration support
109
+ legacyCompatibility?: boolean
110
+
111
+ // Performance hints
112
+ performanceHints?: {
113
+ batchRequests?: boolean
114
+ cacheResponses?: boolean
115
+ preloadSchemas?: boolean
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Enhanced validation result with warnings and recommendations
121
+ */
122
+ export interface EnhancedValidationResult<T> {
123
+ isValid: boolean
124
+ data?: T
125
+ errors: string[]
126
+ warnings: string[]
127
+ recommendations: string[]
128
+ performance: {
129
+ validationTime: number
130
+ memoryUsage?: number
131
+ cacheHit?: boolean
132
+ }
133
+ metadata: {
134
+ version: string
135
+ timestamp: number
136
+ validator: string
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Configuration validation options
142
+ */
143
+ export interface ValidationOptions {
144
+ strict?: boolean
145
+ includeWarnings?: boolean
146
+ includeRecommendations?: boolean
147
+ includePerformanceHints?: boolean
148
+ environment?: string
149
+ legacyMode?: boolean
150
+ }
151
+
152
+ // =============================================================================
153
+ // CONFIGURATION VALIDATOR CLASS
154
+ // =============================================================================
155
+
156
+ /**
157
+ * Universal configuration validator compatible with all KnishIO SDKs
158
+ * Provides enhanced validation with warnings, recommendations, and performance hints
159
+ */
160
+ export class ConfigValidator {
161
+ private static instance: ConfigValidator
162
+ private validationCache = new Map<string, EnhancedValidationResult<any>>()
163
+ private performanceMetrics: Array<{ timestamp: number; duration: number }> = []
164
+
165
+ private constructor() {}
166
+
167
+ static getInstance(): ConfigValidator {
168
+ if (!ConfigValidator.instance) {
169
+ ConfigValidator.instance = new ConfigValidator()
170
+ }
171
+ return ConfigValidator.instance
172
+ }
173
+
174
+ /**
175
+ * Validate client configuration with enhanced error reporting
176
+ */
177
+ static validateClientConfig(
178
+ config: unknown,
179
+ options: ValidationOptions = {}
180
+ ): EnhancedValidationResult<UniversalClientConfig> {
181
+ return ConfigValidator.getInstance().validateConfig(config, options)
182
+ }
183
+
184
+ /**
185
+ * Internal validation implementation
186
+ */
187
+ private validateConfig(
188
+ config: unknown,
189
+ options: ValidationOptions = {}
190
+ ): EnhancedValidationResult<UniversalClientConfig> {
191
+ const startTime = performance.now()
192
+ const cacheKey = this.generateCacheKey(config, options)
193
+
194
+ // Check cache if not in strict mode
195
+ if (!options.strict && this.validationCache.has(cacheKey)) {
196
+ const cached = this.validationCache.get(cacheKey)!
197
+ cached.performance.cacheHit = true
198
+ return cached
199
+ }
200
+
201
+ const result: EnhancedValidationResult<UniversalClientConfig> = {
202
+ isValid: true,
203
+ errors: [],
204
+ warnings: [],
205
+ recommendations: [],
206
+ performance: {
207
+ validationTime: 0,
208
+ cacheHit: false
209
+ },
210
+ metadata: {
211
+ version: '2.0.0',
212
+ timestamp: Date.now(),
213
+ validator: 'ConfigValidator'
214
+ }
215
+ }
216
+
217
+ try {
218
+ // Core validation
219
+ const coreValidation = this.validateCoreConfig(config)
220
+ if (!coreValidation.isValid) {
221
+ result.isValid = false
222
+ result.errors.push(...coreValidation.errors)
223
+ return result
224
+ }
225
+
226
+ result.data = coreValidation.data
227
+
228
+ // Enhanced validations
229
+ if (options.includeWarnings !== false) {
230
+ result.warnings.push(...this.generateWarnings(result.data))
231
+ }
232
+
233
+ if (options.includeRecommendations !== false) {
234
+ result.recommendations.push(...this.generateRecommendations(result.data, options))
235
+ }
236
+
237
+ // Performance validation
238
+ if (options.includePerformanceHints !== false) {
239
+ result.warnings.push(...this.generatePerformanceWarnings(result.data))
240
+ }
241
+
242
+ } catch (error) {
243
+ result.isValid = false
244
+ result.errors.push(`Validation failed: ${error instanceof Error ? error.message : String(error)}`)
245
+ }
246
+
247
+ // Record performance metrics
248
+ const endTime = performance.now()
249
+ result.performance.validationTime = endTime - startTime
250
+ this.recordPerformanceMetric(result.performance.validationTime)
251
+
252
+ // Cache result
253
+ this.validationCache.set(cacheKey, result)
254
+ this.cleanupCache()
255
+
256
+ return result
257
+ }
258
+
259
+ /**
260
+ * Core configuration validation
261
+ */
262
+ private validateCoreConfig(config: unknown): EnhancedValidationResult<UniversalClientConfig> {
263
+ const errors: string[] = []
264
+
265
+ if (!config || typeof config !== 'object') {
266
+ return {
267
+ isValid: false,
268
+ errors: ['Configuration must be an object'],
269
+ warnings: [],
270
+ recommendations: [],
271
+ performance: { validationTime: 0 },
272
+ metadata: { version: '2.0.0', timestamp: Date.now(), validator: 'ConfigValidator' }
273
+ }
274
+ }
275
+
276
+ const typedConfig = config as Record<string, any>
277
+
278
+ // Validate required URI field
279
+ if (!typedConfig.uri) {
280
+ errors.push('URI is required')
281
+ } else if (typeof typedConfig.uri !== 'string' && !Array.isArray(typedConfig.uri)) {
282
+ errors.push('URI must be a string or array of strings')
283
+ } else if (Array.isArray(typedConfig.uri)) {
284
+ if (typedConfig.uri.length === 0) {
285
+ errors.push('URI array cannot be empty')
286
+ } else if (!typedConfig.uri.every(u => typeof u === 'string' && u.length > 0)) {
287
+ errors.push('All URI entries must be non-empty strings')
288
+ }
289
+ } else if (typeof typedConfig.uri === 'string' && typedConfig.uri.length === 0) {
290
+ errors.push('URI cannot be empty')
291
+ }
292
+
293
+ // Validate optional fields with type checking
294
+ if (typedConfig.cellSlug !== undefined && typedConfig.cellSlug !== null && typeof typedConfig.cellSlug !== 'string') {
295
+ errors.push('cellSlug must be a string or null')
296
+ }
297
+
298
+ if (typedConfig.timeout !== undefined && (typeof typedConfig.timeout !== 'number' || typedConfig.timeout < 0)) {
299
+ errors.push('timeout must be a positive number')
300
+ }
301
+
302
+ if (typedConfig.retries !== undefined && (typeof typedConfig.retries !== 'number' || typedConfig.retries < 0)) {
303
+ errors.push('retries must be a non-negative number')
304
+ }
305
+
306
+ if (typedConfig.logging !== undefined && typeof typedConfig.logging !== 'boolean') {
307
+ errors.push('logging must be a boolean')
308
+ }
309
+
310
+ if (typedConfig.serverSdkVersion !== undefined && (typeof typedConfig.serverSdkVersion !== 'number' || typedConfig.serverSdkVersion < 1)) {
311
+ errors.push('serverSdkVersion must be a positive number')
312
+ }
313
+
314
+ if (errors.length > 0) {
315
+ return {
316
+ isValid: false,
317
+ errors,
318
+ warnings: [],
319
+ recommendations: [],
320
+ performance: { validationTime: 0 },
321
+ metadata: { version: '2.0.0', timestamp: Date.now(), validator: 'ConfigValidator' }
322
+ }
323
+ }
324
+
325
+ // Build validated config with defaults
326
+ const validatedConfig: UniversalClientConfig = {
327
+ uri: typedConfig.uri,
328
+ cellSlug: typedConfig.cellSlug || null,
329
+ timeout: typedConfig.timeout || 30000,
330
+ retries: typedConfig.retries || 3,
331
+ retryDelay: typedConfig.retryDelay || 1000,
332
+ logging: typedConfig.logging || false,
333
+ serverSdkVersion: typedConfig.serverSdkVersion || 3,
334
+ strictMode: typedConfig.strictMode || false,
335
+ encryption: typedConfig.encryption || false,
336
+ socket: typedConfig.socket || null,
337
+ client: typedConfig.client || null,
338
+ environment: typedConfig.environment || 'development',
339
+ legacyCompatibility: typedConfig.legacyCompatibility || false,
340
+ connectionPoolSize: typedConfig.connectionPoolSize || 10,
341
+ keepAlive: typedConfig.keepAlive !== false,
342
+ compression: typedConfig.compression !== false,
343
+ performanceHints: {
344
+ batchRequests: typedConfig.performanceHints?.batchRequests !== false,
345
+ cacheResponses: typedConfig.performanceHints?.cacheResponses !== false,
346
+ preloadSchemas: typedConfig.performanceHints?.preloadSchemas !== false,
347
+ ...(typedConfig.performanceHints || {})
348
+ }
349
+ }
350
+
351
+ return {
352
+ isValid: true,
353
+ data: validatedConfig,
354
+ errors: [],
355
+ warnings: [],
356
+ recommendations: [],
357
+ performance: { validationTime: 0 },
358
+ metadata: { version: '2.0.0', timestamp: Date.now(), validator: 'ConfigValidator' }
359
+ }
360
+ }
361
+
362
+ /**
363
+ * Generate configuration warnings
364
+ */
365
+ private generateWarnings(config: UniversalClientConfig): string[] {
366
+ const warnings: string[] = []
367
+
368
+ // URI warnings
369
+ if (typeof config.uri === 'string' && !config.uri.startsWith('http')) {
370
+ warnings.push('URI should use HTTP/HTTPS protocol')
371
+ }
372
+
373
+ // Timeout warnings
374
+ if (config.timeout && config.timeout > 60000) {
375
+ warnings.push('Timeout is very high (>60s), this may cause poor user experience')
376
+ }
377
+
378
+ if (config.timeout && config.timeout < 5000) {
379
+ warnings.push('Timeout is very low (<5s), this may cause premature failures')
380
+ }
381
+
382
+ // Performance warnings
383
+ if (config.logging && config.environment === 'production') {
384
+ warnings.push('Logging is enabled in production environment')
385
+ }
386
+
387
+ if (config.serverSdkVersion && config.serverSdkVersion < 3) {
388
+ warnings.push('Using older server SDK version, consider upgrading for better features and security')
389
+ }
390
+
391
+ // Security warnings
392
+ if (!config.encryption && config.environment === 'production') {
393
+ warnings.push('Encryption is disabled in production environment')
394
+ }
395
+
396
+ return warnings
397
+ }
398
+
399
+ /**
400
+ * Generate configuration recommendations
401
+ */
402
+ private generateRecommendations(config: UniversalClientConfig, options: ValidationOptions): string[] {
403
+ const recommendations: string[] = []
404
+
405
+ // Performance recommendations
406
+ if (config.performanceHints?.batchRequests === false) {
407
+ recommendations.push('Enable request batching for better performance')
408
+ }
409
+
410
+ if (config.performanceHints?.cacheResponses === false) {
411
+ recommendations.push('Enable response caching to reduce network overhead')
412
+ }
413
+
414
+ // Environment-specific recommendations
415
+ if (options.environment === 'production') {
416
+ recommendations.push('Consider enabling connection pooling for production environments')
417
+
418
+ if (!config.compression) {
419
+ recommendations.push('Enable compression to reduce bandwidth usage in production')
420
+ }
421
+ }
422
+
423
+ // Security recommendations
424
+ if (config.serverSdkVersion && config.serverSdkVersion >= 4) {
425
+ recommendations.push('Consider enabling strict mode for enhanced security with SDK v4+')
426
+ }
427
+
428
+ return recommendations
429
+ }
430
+
431
+ /**
432
+ * Generate performance warnings
433
+ */
434
+ private generatePerformanceWarnings(config: UniversalClientConfig): string[] {
435
+ const warnings: string[] = []
436
+
437
+ if (config.connectionPoolSize && config.connectionPoolSize > 50) {
438
+ warnings.push('Large connection pool size may consume excessive memory')
439
+ }
440
+
441
+ if (!config.keepAlive) {
442
+ warnings.push('Disabling keep-alive may impact performance with frequent requests')
443
+ }
444
+
445
+ return warnings
446
+ }
447
+
448
+ /**
449
+ * Generate cache key for configuration
450
+ */
451
+ private generateCacheKey(config: unknown, options: ValidationOptions): string {
452
+ return JSON.stringify({ config, options })
453
+ }
454
+
455
+ /**
456
+ * Record performance metric
457
+ */
458
+ private recordPerformanceMetric(duration: number): void {
459
+ this.performanceMetrics.push({
460
+ timestamp: Date.now(),
461
+ duration
462
+ })
463
+
464
+ // Keep only last 1000 metrics
465
+ if (this.performanceMetrics.length > 1000) {
466
+ this.performanceMetrics = this.performanceMetrics.slice(-1000)
467
+ }
468
+ }
469
+
470
+ /**
471
+ * Clean up validation cache
472
+ */
473
+ private cleanupCache(): void {
474
+ if (this.validationCache.size > 500) {
475
+ // Remove oldest entries
476
+ const entries = Array.from(this.validationCache.entries())
477
+ const toKeep = entries.slice(-250)
478
+ this.validationCache.clear()
479
+ toKeep.forEach(([key, value]) => this.validationCache.set(key, value))
480
+ }
481
+ }
482
+
483
+ /**
484
+ * Get validation statistics
485
+ */
486
+ getValidationStats(): {
487
+ totalValidations: number
488
+ cacheSize: number
489
+ averageValidationTime: number
490
+ recentValidations: number
491
+ } {
492
+ const recent = this.performanceMetrics.slice(-100)
493
+ const avgTime = recent.reduce((sum, m) => sum + m.duration, 0) / recent.length || 0
494
+
495
+ return {
496
+ totalValidations: this.performanceMetrics.length,
497
+ cacheSize: this.validationCache.size,
498
+ averageValidationTime: Math.round(avgTime * 100) / 100,
499
+ recentValidations: recent.length
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Clear validation cache and metrics
505
+ */
506
+ clearCache(): void {
507
+ this.validationCache.clear()
508
+ this.performanceMetrics = []
509
+ }
510
+ }
511
+
512
+ // =============================================================================
513
+ // ENVIRONMENT CONFIGURATION INTEGRATION
514
+ // =============================================================================
515
+
516
+ /**
517
+ * Load configuration from environment variables
518
+ */
519
+ export function loadEnvironmentConfig(): Partial<UniversalClientConfig> {
520
+ const config: Partial<UniversalClientConfig> = {}
521
+
522
+ if (process.env.KNISHIO_NODE_URI) {
523
+ config.uri = process.env.KNISHIO_NODE_URI.includes(',')
524
+ ? process.env.KNISHIO_NODE_URI.split(',').map(u => u.trim())
525
+ : process.env.KNISHIO_NODE_URI
526
+ }
527
+
528
+ if (process.env.KNISHIO_CELL_SLUG) {
529
+ config.cellSlug = process.env.KNISHIO_CELL_SLUG
530
+ }
531
+
532
+ if (process.env.KNISHIO_TIMEOUT) {
533
+ const timeout = parseInt(process.env.KNISHIO_TIMEOUT, 10)
534
+ if (!isNaN(timeout)) {
535
+ config.timeout = timeout
536
+ }
537
+ }
538
+
539
+ if (process.env.KNISHIO_LOGGING) {
540
+ config.logging = process.env.KNISHIO_LOGGING.toLowerCase() === 'true'
541
+ }
542
+
543
+ if (process.env.KNISHIO_SERVER_SDK_VERSION) {
544
+ const version = parseInt(process.env.KNISHIO_SERVER_SDK_VERSION, 10)
545
+ if (!isNaN(version)) {
546
+ config.serverSdkVersion = version
547
+ }
548
+ }
549
+
550
+ if (process.env.NODE_ENV) {
551
+ config.environment = process.env.NODE_ENV as any
552
+ }
553
+
554
+ return config
555
+ }
556
+
557
+ /**
558
+ * Merge configurations with precedence handling
559
+ */
560
+ export function mergeConfigurations(
561
+ base: Partial<UniversalClientConfig>,
562
+ override: Partial<UniversalClientConfig>
563
+ ): UniversalClientConfig {
564
+ const merged = { ...base, ...override } as UniversalClientConfig
565
+
566
+ // Ensure required fields have defaults
567
+ if (!merged.uri) {
568
+ throw new Error('URI is required in configuration')
569
+ }
570
+
571
+ // Apply intelligent defaults
572
+ merged.timeout = merged.timeout || 30000
573
+ merged.retries = merged.retries || 3
574
+ merged.retryDelay = merged.retryDelay || 1000
575
+ merged.logging = merged.logging || false
576
+ merged.serverSdkVersion = merged.serverSdkVersion || 3
577
+ merged.environment = merged.environment || 'development'
578
+
579
+ return merged
580
+ }