homebridge 2.0.0-alpha.40 → 2.0.0-alpha.42

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 (92) hide show
  1. package/config-sample.json +1 -12
  2. package/dist/api.d.ts +46 -35
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/api.js +41 -35
  5. package/dist/api.js.map +1 -1
  6. package/dist/bridgeService.d.ts +7 -15
  7. package/dist/bridgeService.d.ts.map +1 -1
  8. package/dist/bridgeService.js +10 -7
  9. package/dist/bridgeService.js.map +1 -1
  10. package/dist/childBridgeFork.d.ts +19 -0
  11. package/dist/childBridgeFork.d.ts.map +1 -1
  12. package/dist/childBridgeFork.js +198 -4
  13. package/dist/childBridgeFork.js.map +1 -1
  14. package/dist/childBridgeService.d.ts +28 -1
  15. package/dist/childBridgeService.d.ts.map +1 -1
  16. package/dist/childBridgeService.js +43 -0
  17. package/dist/childBridgeService.js.map +1 -1
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +3 -1
  20. package/dist/cli.js.map +1 -1
  21. package/dist/index.d.ts +9 -5
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +5 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/ipcService.d.ts +21 -3
  26. package/dist/ipcService.d.ts.map +1 -1
  27. package/dist/ipcService.js +15 -0
  28. package/dist/ipcService.js.map +1 -1
  29. package/dist/matter/index.d.ts +11 -0
  30. package/dist/matter/index.d.ts.map +1 -0
  31. package/dist/matter/index.js +11 -0
  32. package/dist/matter/index.js.map +1 -0
  33. package/dist/matter/matterConfigValidator.d.ts +26 -0
  34. package/dist/matter/matterConfigValidator.d.ts.map +1 -0
  35. package/dist/matter/matterConfigValidator.js +171 -0
  36. package/dist/matter/matterConfigValidator.js.map +1 -0
  37. package/dist/matter/matterDiagnostics.d.ts +121 -0
  38. package/dist/matter/matterDiagnostics.d.ts.map +1 -0
  39. package/dist/matter/matterDiagnostics.js +323 -0
  40. package/dist/matter/matterDiagnostics.js.map +1 -0
  41. package/dist/matter/matterErrorHandler.d.ts +94 -0
  42. package/dist/matter/matterErrorHandler.d.ts.map +1 -0
  43. package/dist/matter/matterErrorHandler.js +472 -0
  44. package/dist/matter/matterErrorHandler.js.map +1 -0
  45. package/dist/matter/matterNetworkMonitor.d.ts +65 -0
  46. package/dist/matter/matterNetworkMonitor.d.ts.map +1 -0
  47. package/dist/matter/matterNetworkMonitor.js +227 -0
  48. package/dist/matter/matterNetworkMonitor.js.map +1 -0
  49. package/dist/matter/matterServer.d.ts +196 -0
  50. package/dist/matter/matterServer.d.ts.map +1 -0
  51. package/dist/matter/matterServer.js +824 -0
  52. package/dist/matter/matterServer.js.map +1 -0
  53. package/dist/matter/matterSharedTypes.d.ts +147 -0
  54. package/dist/matter/matterSharedTypes.d.ts.map +1 -0
  55. package/dist/matter/matterSharedTypes.js +51 -0
  56. package/dist/matter/matterSharedTypes.js.map +1 -0
  57. package/dist/matter/matterStorage.d.ts +112 -0
  58. package/dist/matter/matterStorage.d.ts.map +1 -0
  59. package/dist/matter/matterStorage.js +355 -0
  60. package/dist/matter/matterStorage.js.map +1 -0
  61. package/dist/matter/matterTypes.d.ts +163 -0
  62. package/dist/matter/matterTypes.d.ts.map +1 -0
  63. package/dist/matter/matterTypes.js +106 -0
  64. package/dist/matter/matterTypes.js.map +1 -0
  65. package/dist/plugin.d.ts.map +1 -1
  66. package/dist/plugin.js +4 -2
  67. package/dist/plugin.js.map +1 -1
  68. package/dist/server.d.ts +18 -4
  69. package/dist/server.d.ts.map +1 -1
  70. package/dist/server.js +361 -51
  71. package/dist/server.js.map +1 -1
  72. package/dist/user.d.ts +1 -0
  73. package/dist/user.d.ts.map +1 -1
  74. package/dist/user.js +3 -0
  75. package/dist/user.js.map +1 -1
  76. package/package.json +12 -13
  77. package/dist/matterConfigValidator.d.ts +0 -34
  78. package/dist/matterConfigValidator.d.ts.map +0 -1
  79. package/dist/matterConfigValidator.js +0 -249
  80. package/dist/matterConfigValidator.js.map +0 -1
  81. package/dist/matterService.d.ts +0 -168
  82. package/dist/matterService.d.ts.map +0 -1
  83. package/dist/matterService.js +0 -677
  84. package/dist/matterService.js.map +0 -1
  85. package/dist/matterTypes.d.ts +0 -20
  86. package/dist/matterTypes.d.ts.map +0 -1
  87. package/dist/matterTypes.js +0 -278
  88. package/dist/matterTypes.js.map +0 -1
  89. package/dist/util/matter-cli.d.ts +0 -3
  90. package/dist/util/matter-cli.d.ts.map +0 -1
  91. package/dist/util/matter-cli.js +0 -211
  92. package/dist/util/matter-cli.js.map +0 -1
@@ -0,0 +1,323 @@
1
+ /* global NodeJS */
2
+ /**
3
+ * Matter Diagnostics
4
+ *
5
+ * Comprehensive diagnostics and health monitoring for Matter integration
6
+ */
7
+ import * as os from 'node:os';
8
+ import process from 'node:process';
9
+ import { Logger } from '../logger.js';
10
+ import { errorHandler } from './matterErrorHandler.js';
11
+ import { networkMonitor } from './matterNetworkMonitor.js';
12
+ const log = Logger.withPrefix('Matter');
13
+ export class MatterDiagnostics {
14
+ static instance;
15
+ performanceMetrics;
16
+ diagnosticInterval = null;
17
+ isDiagnosticsEnabled = false;
18
+ lastHealthStatus = null;
19
+ constructor() {
20
+ this.performanceMetrics = {
21
+ syncTimes: [],
22
+ startTime: new Date(),
23
+ };
24
+ }
25
+ static getInstance() {
26
+ if (!MatterDiagnostics.instance) {
27
+ MatterDiagnostics.instance = new MatterDiagnostics();
28
+ }
29
+ return MatterDiagnostics.instance;
30
+ }
31
+ /**
32
+ * Start diagnostics collection
33
+ */
34
+ startDiagnostics(intervalMs = 60000) {
35
+ if (this.isDiagnosticsEnabled) {
36
+ return;
37
+ }
38
+ this.isDiagnosticsEnabled = true;
39
+ log.debug('Starting Matter diagnostics collection');
40
+ // Collect diagnostics periodically
41
+ this.diagnosticInterval = setInterval(() => {
42
+ // Fire-and-forget with error handling
43
+ this.collectAndLogDiagnostics().catch((error) => {
44
+ log.debug('Failed to collect diagnostics:', error);
45
+ });
46
+ }, intervalMs);
47
+ }
48
+ /**
49
+ * Stop diagnostics collection
50
+ */
51
+ stopDiagnostics() {
52
+ if (this.diagnosticInterval) {
53
+ clearInterval(this.diagnosticInterval);
54
+ this.diagnosticInterval = null;
55
+ }
56
+ this.isDiagnosticsEnabled = false;
57
+ log.debug('Stopped Matter diagnostics collection');
58
+ }
59
+ /**
60
+ * Record sync performance
61
+ */
62
+ recordSyncTime(timeMs) {
63
+ this.performanceMetrics.syncTimes.push(timeMs);
64
+ // Keep only last 100 measurements
65
+ if (this.performanceMetrics.syncTimes.length > 100) {
66
+ this.performanceMetrics.syncTimes.shift();
67
+ }
68
+ // Log warning for slow syncs
69
+ if (timeMs > 1000) {
70
+ log.warn(`Slow Matter sync detected: ${timeMs}ms`);
71
+ }
72
+ }
73
+ /**
74
+ * Collect all diagnostic information
75
+ */
76
+ async collectDiagnostics(matterInfo) {
77
+ return {
78
+ timestamp: new Date(),
79
+ system: this.collectSystemInfo(),
80
+ matter: matterInfo || this.getDefaultMatterInfo(),
81
+ network: this.collectNetworkInfo(),
82
+ errors: this.collectErrorInfo(),
83
+ performance: this.collectPerformanceInfo(),
84
+ health: this.assessHealth(),
85
+ };
86
+ }
87
+ /**
88
+ * Collect system information
89
+ */
90
+ collectSystemInfo() {
91
+ const totalMem = os.totalmem();
92
+ const freeMem = os.freemem();
93
+ const usedMem = totalMem - freeMem;
94
+ const cpus = os.cpus();
95
+ const avgLoad = os.loadavg()[0];
96
+ return {
97
+ platform: os.platform(),
98
+ arch: os.arch(),
99
+ nodeVersion: process.version,
100
+ uptime: os.uptime(),
101
+ memory: {
102
+ total: totalMem,
103
+ free: freeMem,
104
+ used: usedMem,
105
+ percentage: (usedMem / totalMem) * 100,
106
+ },
107
+ cpu: {
108
+ model: cpus[0]?.model || 'Unknown',
109
+ cores: cpus.length,
110
+ usage: avgLoad,
111
+ },
112
+ };
113
+ }
114
+ /**
115
+ * Get default Matter info
116
+ */
117
+ getDefaultMatterInfo() {
118
+ return {
119
+ enabled: false,
120
+ initialized: false,
121
+ running: false,
122
+ deviceCount: 0,
123
+ bridgeCount: 0,
124
+ };
125
+ }
126
+ /**
127
+ * Collect network information
128
+ */
129
+ collectNetworkInfo() {
130
+ const status = networkMonitor.getStatus();
131
+ return {
132
+ online: status.isOnline,
133
+ interfaces: status.interfaces,
134
+ primaryInterface: status.primaryInterface,
135
+ lastCheck: status.lastCheck,
136
+ };
137
+ }
138
+ /**
139
+ * Collect error information
140
+ */
141
+ collectErrorInfo() {
142
+ const errorStats = errorHandler.getErrorStats();
143
+ let total = 0;
144
+ const byType = {};
145
+ const recent = [];
146
+ for (const [type, stats] of Object.entries(errorStats)) {
147
+ total += stats.count;
148
+ byType[type] = stats.count;
149
+ if (stats.lastError) {
150
+ recent.push({
151
+ type,
152
+ message: stats.lastError.message,
153
+ timestamp: stats.lastError.timestamp,
154
+ });
155
+ }
156
+ }
157
+ // Sort recent errors by timestamp
158
+ recent.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
159
+ return {
160
+ total,
161
+ byType,
162
+ recent: recent.slice(0, 10), // Keep only 10 most recent
163
+ };
164
+ }
165
+ /**
166
+ * Collect performance information
167
+ */
168
+ collectPerformanceInfo() {
169
+ const syncTimes = this.performanceMetrics.syncTimes;
170
+ const avgSyncTime = syncTimes.length > 0
171
+ ? syncTimes.reduce((a, b) => a + b, 0) / syncTimes.length
172
+ : 0;
173
+ return {
174
+ syncLatency: syncTimes.slice(-10), // Last 10 measurements
175
+ averageSyncTime: avgSyncTime,
176
+ memoryUsage: process.memoryUsage().heapUsed,
177
+ eventLoopLag: 0, // Would need additional monitoring
178
+ };
179
+ }
180
+ /**
181
+ * Assess overall health
182
+ */
183
+ assessHealth() {
184
+ const issues = [];
185
+ const recommendations = [];
186
+ // Check network
187
+ const networkStatus = networkMonitor.getStatus();
188
+ if (!networkStatus.isOnline) {
189
+ issues.push('Network is offline');
190
+ recommendations.push('Check network connectivity');
191
+ }
192
+ else if (networkStatus.consecutiveFailures > 0) {
193
+ issues.push('Intermittent network issues detected');
194
+ recommendations.push('Monitor network stability');
195
+ }
196
+ // Check errors
197
+ const errorStats = errorHandler.getErrorStats();
198
+ const totalErrors = Object.values(errorStats)
199
+ .reduce((sum, stat) => sum + stat.count, 0);
200
+ if (totalErrors > 10) {
201
+ issues.push(`High error rate: ${totalErrors} errors`);
202
+ recommendations.push('Review error logs for patterns');
203
+ }
204
+ // Check performance
205
+ const perfInfo = this.collectPerformanceInfo();
206
+ if (perfInfo.averageSyncTime > 500) {
207
+ issues.push(`Slow sync performance: ${perfInfo.averageSyncTime.toFixed(0)}ms average`);
208
+ recommendations.push('Consider reducing device count or optimizing sync frequency');
209
+ }
210
+ // Check memory (raised threshold to 95% to reduce false positives)
211
+ const systemInfo = this.collectSystemInfo();
212
+ if (systemInfo.memory.percentage > 95) {
213
+ issues.push(`High memory usage: ${systemInfo.memory.percentage.toFixed(1)}%`);
214
+ recommendations.push('Consider increasing system memory or reducing load');
215
+ }
216
+ else if (systemInfo.memory.percentage > 90) {
217
+ // Only log in debug mode for 90-95% range
218
+ log.debug(`Memory usage at ${systemInfo.memory.percentage.toFixed(1)}%`);
219
+ }
220
+ // Determine overall health
221
+ let overall;
222
+ if (issues.length === 0) {
223
+ overall = 'healthy';
224
+ }
225
+ else if (issues.length <= 2) {
226
+ overall = 'degraded';
227
+ }
228
+ else {
229
+ overall = 'unhealthy';
230
+ }
231
+ return {
232
+ overall,
233
+ issues,
234
+ recommendations,
235
+ };
236
+ }
237
+ /**
238
+ * Collect and log diagnostics
239
+ */
240
+ async collectAndLogDiagnostics() {
241
+ const diagnostics = await this.collectDiagnostics();
242
+ // Only log health status if it changed or is unhealthy
243
+ if (diagnostics.health.overall !== this.lastHealthStatus) {
244
+ this.lastHealthStatus = diagnostics.health.overall;
245
+ if (diagnostics.health.overall !== 'healthy') {
246
+ log.warn(`Matter health status: ${diagnostics.health.overall}`);
247
+ for (const issue of diagnostics.health.issues) {
248
+ log.warn(` - ${issue}`);
249
+ }
250
+ for (const recommendation of diagnostics.health.recommendations) {
251
+ log.info(` 💡 ${recommendation}`);
252
+ }
253
+ }
254
+ else {
255
+ log.info('Matter health status: healthy');
256
+ }
257
+ }
258
+ // Log debug information
259
+ log.debug('Matter diagnostics:', {
260
+ health: diagnostics.health.overall,
261
+ errors: diagnostics.errors.total,
262
+ devices: diagnostics.matter.deviceCount,
263
+ avgSyncTime: `${diagnostics.performance.averageSyncTime.toFixed(0)}ms`,
264
+ memory: `${(diagnostics.system.memory.percentage).toFixed(1)}%`,
265
+ });
266
+ }
267
+ /**
268
+ * Generate diagnostic report
269
+ */
270
+ async generateReport(matterInfo) {
271
+ const diagnostics = await this.collectDiagnostics(matterInfo);
272
+ return `
273
+ Matter Diagnostics Report
274
+ ========================
275
+ Generated: ${diagnostics.timestamp.toISOString()}
276
+
277
+ System Information
278
+ ------------------
279
+ Platform: ${diagnostics.system.platform} (${diagnostics.system.arch})
280
+ Node Version: ${diagnostics.system.nodeVersion}
281
+ System Uptime: ${(diagnostics.system.uptime / 3600).toFixed(1)} hours
282
+ Memory: ${(diagnostics.system.memory.used / 1024 / 1024 / 1024).toFixed(1)}GB / ${(diagnostics.system.memory.total / 1024 / 1024 / 1024).toFixed(1)}GB (${diagnostics.system.memory.percentage.toFixed(1)}%)
283
+ CPU: ${diagnostics.system.cpu.model} (${diagnostics.system.cpu.cores} cores)
284
+
285
+ Matter Status
286
+ -------------
287
+ Enabled: ${diagnostics.matter.enabled}
288
+ Initialized: ${diagnostics.matter.initialized}
289
+ Running: ${diagnostics.matter.running}
290
+ Port: ${diagnostics.matter.port || 'N/A'}
291
+ Devices: ${diagnostics.matter.deviceCount}
292
+ Bridges: ${diagnostics.matter.bridgeCount}
293
+
294
+ Network Status
295
+ --------------
296
+ Online: ${diagnostics.network.online}
297
+ Interfaces: ${diagnostics.network.interfaces.join(', ') || 'None'}
298
+ Primary: ${diagnostics.network.primaryInterface || 'N/A'}
299
+ Last Check: ${diagnostics.network.lastCheck.toISOString()}
300
+
301
+ Error Summary
302
+ -------------
303
+ Total Errors: ${diagnostics.errors.total}
304
+ ${Object.entries(diagnostics.errors.byType)
305
+ .map(([type, count]) => ` ${type}: ${count}`)
306
+ .join('\n')}
307
+
308
+ Performance
309
+ -----------
310
+ Average Sync Time: ${diagnostics.performance.averageSyncTime.toFixed(0)}ms
311
+ Memory Usage: ${(diagnostics.performance.memoryUsage / 1024 / 1024).toFixed(1)}MB
312
+
313
+ Health Assessment
314
+ -----------------
315
+ Overall: ${diagnostics.health.overall.toUpperCase()}
316
+ ${diagnostics.health.issues.length > 0 ? `Issues:\n${diagnostics.health.issues.map(i => ` - ${i}`).join('\n')}` : ''}
317
+ ${diagnostics.health.recommendations.length > 0 ? `Recommendations:\n${diagnostics.health.recommendations.map(r => ` - ${r}`).join('\n')}` : ''}
318
+ `;
319
+ }
320
+ }
321
+ // Export singleton instance
322
+ export const diagnostics = MatterDiagnostics.getInstance();
323
+ //# sourceMappingURL=matterDiagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matterDiagnostics.js","sourceRoot":"","sources":["../../src/matter/matterDiagnostics.ts"],"names":[],"mappings":"AAAA,mBAAmB;AAEnB;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAA;AAC7B,OAAO,OAAO,MAAM,cAAc,CAAA;AAElC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAA;AAE1D,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;AAsEvC,MAAM,OAAO,iBAAiB;IACpB,MAAM,CAAC,QAAQ,CAAmB;IAClC,kBAAkB,CAGzB;IAEO,kBAAkB,GAA0B,IAAI,CAAA;IAChD,oBAAoB,GAAG,KAAK,CAAA;IAC5B,gBAAgB,GAAgD,IAAI,CAAA;IA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CAAC,YAAY,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE;EACnH,WAAW,CAAC,MAAM,CAAC,eAAe,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,qBAAqB,WAAW,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE;CAC/I,CAAA;IACC,CAAC;CACF;AAED,4BAA4B;AAC5B,MAAM,CAAC,MAAM,WAAW,GAAG,iBAAiB,CAAC,WAAW,EAAE,CAAA"}
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Matter Error Handler
3
+ *
4
+ * Centralized error handling and recovery for Matter.js integration
5
+ * with circuit breaker pattern and contextual recovery
6
+ */
7
+ import { MatterCommissioningError, MatterDeviceError, MatterError, MatterErrorType, MatterNetworkError, MatterStorageError } from './matterTypes.js';
8
+ export { MatterCommissioningError, MatterDeviceError, MatterError, MatterErrorType, MatterNetworkError, MatterStorageError };
9
+ /**
10
+ * Circuit breaker states
11
+ */
12
+ declare enum CircuitState {
13
+ CLOSED = "CLOSED",// Normal operation
14
+ OPEN = "OPEN",// Failure threshold exceeded, blocking requests
15
+ HALF_OPEN = "HALF_OPEN"
16
+ }
17
+ export declare class MatterErrorHandler {
18
+ private static instance;
19
+ private errorCount;
20
+ private lastErrors;
21
+ private recoveryCallbacks;
22
+ private circuitBreakers;
23
+ private recoveryContexts;
24
+ private readonly MAX_RECOVERY_ATTEMPTS;
25
+ private constructor();
26
+ static getInstance(): MatterErrorHandler;
27
+ /**
28
+ * Handle a Matter error with context-aware recovery
29
+ */
30
+ handleError(error: Error | MatterError, context?: string): Promise<void>;
31
+ /**
32
+ * Categorize error into Matter error types
33
+ */
34
+ private categorizeError;
35
+ /**
36
+ * Log error with appropriate severity
37
+ */
38
+ private logError;
39
+ /**
40
+ * Get error type from MatterError
41
+ */
42
+ private getErrorType;
43
+ /**
44
+ * Track error occurrences with bounds checking
45
+ */
46
+ private trackError;
47
+ /**
48
+ * Clear errors for a specific type
49
+ */
50
+ private clearErrors;
51
+ /**
52
+ * Attempt contextual recovery from error
53
+ */
54
+ private attemptContextualRecovery;
55
+ /**
56
+ * Get or create a circuit breaker for an error type
57
+ */
58
+ private getOrCreateCircuitBreaker;
59
+ /**
60
+ * Check if we should attempt recovery
61
+ */
62
+ private shouldAttemptRecovery;
63
+ /**
64
+ * Get contextual delay based on error type and attempt count
65
+ */
66
+ private getContextualDelay;
67
+ /**
68
+ * Register a recovery callback for specific error type
69
+ */
70
+ registerRecoveryCallback(type: MatterErrorType, callback: () => Promise<void>): void;
71
+ /**
72
+ * Reset error counts (useful after successful recovery)
73
+ */
74
+ resetErrorCount(type?: MatterErrorType): void;
75
+ /**
76
+ * Get error statistics
77
+ */
78
+ getErrorStats(): Map<MatterErrorType, {
79
+ count: number;
80
+ lastError?: MatterError;
81
+ circuitState?: CircuitState;
82
+ recoveryAttempts?: number;
83
+ }>;
84
+ /**
85
+ * Create a wrapped function with error handling
86
+ */
87
+ wrapAsync<T extends (...args: any[]) => Promise<any>>(fn: T, context: string): T;
88
+ /**
89
+ * Create a wrapped function with error suppression
90
+ */
91
+ wrapAsyncSafe<T extends (...args: any[]) => Promise<any>>(fn: T, context: string, defaultValue?: ReturnType<T>): T;
92
+ }
93
+ export declare const errorHandler: MatterErrorHandler;
94
+ //# sourceMappingURL=matterErrorHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matterErrorHandler.d.ts","sourceRoot":"","sources":["../../src/matter/matterErrorHandler.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,WAAW,EACX,eAAe,EACf,k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