mastercontroller 1.2.12 → 1.2.13

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.
@@ -0,0 +1,233 @@
1
+ /**
2
+ * PerformanceMonitor - Track and report SSR performance metrics
3
+ * Version: 1.0.0
4
+ */
5
+
6
+ const { MasterControllerError } = require('../MasterErrorHandler');
7
+
8
+ const isDevelopment = process.env.NODE_ENV !== 'production' && process.env.master === 'development';
9
+
10
+ // Performance thresholds (milliseconds)
11
+ const THRESHOLDS = {
12
+ SLOW_RENDER: 100, // Warn if component takes >100ms to render
13
+ VERY_SLOW_RENDER: 500, // Error if component takes >500ms
14
+ TOTAL_SSR: 3000 // Warn if total SSR time exceeds 3s
15
+ };
16
+
17
+ class PerformanceMonitor {
18
+ constructor() {
19
+ this.metrics = {
20
+ totalStartTime: null,
21
+ totalEndTime: null,
22
+ components: new Map(),
23
+ slowComponents: [],
24
+ totalRenderTime: 0,
25
+ componentCount: 0
26
+ };
27
+
28
+ this.enabled = isDevelopment || process.env.MC_PERF_MONITOR === 'true';
29
+ }
30
+
31
+ /**
32
+ * Start monitoring SSR session
33
+ */
34
+ startSession() {
35
+ if (!this.enabled) return;
36
+ this.metrics.totalStartTime = Date.now();
37
+ this.metrics.components.clear();
38
+ this.metrics.slowComponents = [];
39
+ this.metrics.totalRenderTime = 0;
40
+ this.metrics.componentCount = 0;
41
+ }
42
+
43
+ /**
44
+ * Record component render time
45
+ */
46
+ recordComponent(componentName, renderTime, filePath = null) {
47
+ if (!this.enabled) return;
48
+
49
+ this.metrics.componentCount++;
50
+ this.metrics.totalRenderTime += renderTime;
51
+
52
+ // Store component metrics
53
+ if (!this.metrics.components.has(componentName)) {
54
+ this.metrics.components.set(componentName, {
55
+ name: componentName,
56
+ renderTime,
57
+ renderCount: 1,
58
+ filePath
59
+ });
60
+ } else {
61
+ const existing = this.metrics.components.get(componentName);
62
+ existing.renderTime += renderTime;
63
+ existing.renderCount++;
64
+ }
65
+
66
+ // Track slow components
67
+ if (renderTime > THRESHOLDS.SLOW_RENDER) {
68
+ this.metrics.slowComponents.push({
69
+ name: componentName,
70
+ renderTime,
71
+ filePath,
72
+ severity: renderTime > THRESHOLDS.VERY_SLOW_RENDER ? 'error' : 'warning'
73
+ });
74
+
75
+ // Warn immediately about slow renders in development
76
+ if (isDevelopment) {
77
+ const severity = renderTime > THRESHOLDS.VERY_SLOW_RENDER ? 'error' : 'warning';
78
+ const message = renderTime > THRESHOLDS.VERY_SLOW_RENDER
79
+ ? `Component rendering VERY slowly (${renderTime}ms > ${THRESHOLDS.VERY_SLOW_RENDER}ms threshold)`
80
+ : `Component rendering slowly (${renderTime}ms > ${THRESHOLDS.SLOW_RENDER}ms threshold)`;
81
+
82
+ const error = new MasterControllerError({
83
+ code: 'MC_ERR_SLOW_RENDER',
84
+ message,
85
+ component: componentName,
86
+ file: filePath,
87
+ details: this._getSuggestions(componentName, renderTime)
88
+ });
89
+
90
+ if (severity === 'error') {
91
+ console.error(error.format());
92
+ } else {
93
+ console.warn(error.format());
94
+ }
95
+ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * End monitoring session and generate report
101
+ */
102
+ endSession() {
103
+ if (!this.enabled) return null;
104
+
105
+ this.metrics.totalEndTime = Date.now();
106
+ const totalTime = this.metrics.totalEndTime - this.metrics.totalStartTime;
107
+
108
+ // Warn about slow total SSR time
109
+ if (totalTime > THRESHOLDS.TOTAL_SSR && isDevelopment) {
110
+ console.warn(
111
+ new MasterControllerError({
112
+ code: 'MC_ERR_SLOW_RENDER',
113
+ message: `Total SSR time exceeded threshold (${totalTime}ms > ${THRESHOLDS.TOTAL_SSR}ms)`,
114
+ details: `Rendered ${this.metrics.componentCount} components. Consider optimizing slow components or using lazy loading.`
115
+ }).format()
116
+ );
117
+ }
118
+
119
+ const report = this._generateReport(totalTime);
120
+
121
+ // Print report in development
122
+ if (isDevelopment) {
123
+ this._printReport(report);
124
+ }
125
+
126
+ return report;
127
+ }
128
+
129
+ /**
130
+ * Generate performance report
131
+ */
132
+ _generateReport(totalTime) {
133
+ // Sort components by render time
134
+ const sortedComponents = Array.from(this.metrics.components.values())
135
+ .sort((a, b) => b.renderTime - a.renderTime);
136
+
137
+ return {
138
+ totalTime,
139
+ componentCount: this.metrics.componentCount,
140
+ averageRenderTime: this.metrics.componentCount > 0
141
+ ? Math.round(this.metrics.totalRenderTime / this.metrics.componentCount)
142
+ : 0,
143
+ slowComponents: this.metrics.slowComponents,
144
+ topComponents: sortedComponents.slice(0, 10),
145
+ summary: {
146
+ fast: sortedComponents.filter(c => c.renderTime <= THRESHOLDS.SLOW_RENDER).length,
147
+ slow: sortedComponents.filter(c => c.renderTime > THRESHOLDS.SLOW_RENDER && c.renderTime <= THRESHOLDS.VERY_SLOW_RENDER).length,
148
+ verySlow: sortedComponents.filter(c => c.renderTime > THRESHOLDS.VERY_SLOW_RENDER).length
149
+ }
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Print formatted performance report
155
+ */
156
+ _printReport(report) {
157
+ console.log('\n' + '═'.repeat(80));
158
+ console.log('🚀 MasterController SSR Performance Report');
159
+ console.log('═'.repeat(80));
160
+ console.log(`Total SSR Time: ${report.totalTime}ms`);
161
+ console.log(`Components Rendered: ${report.componentCount}`);
162
+ console.log(`Average Render Time: ${report.averageRenderTime}ms`);
163
+ console.log(`\nPerformance Summary:`);
164
+ console.log(` ✅ Fast (<${THRESHOLDS.SLOW_RENDER}ms): ${report.summary.fast}`);
165
+ console.log(` ⚠️ Slow (${THRESHOLDS.SLOW_RENDER}-${THRESHOLDS.VERY_SLOW_RENDER}ms): ${report.summary.slow}`);
166
+ console.log(` ❌ Very Slow (>${THRESHOLDS.VERY_SLOW_RENDER}ms): ${report.summary.verySlow}`);
167
+
168
+ if (report.topComponents.length > 0) {
169
+ console.log(`\nTop ${Math.min(10, report.topComponents.length)} Slowest Components:`);
170
+ report.topComponents.forEach((comp, index) => {
171
+ const icon = comp.renderTime > THRESHOLDS.VERY_SLOW_RENDER ? '❌' :
172
+ comp.renderTime > THRESHOLDS.SLOW_RENDER ? '⚠️' : '✅';
173
+ console.log(` ${icon} ${index + 1}. ${comp.name}: ${comp.renderTime}ms (${comp.renderCount} render${comp.renderCount > 1 ? 's' : ''})`);
174
+ });
175
+ }
176
+
177
+ console.log('═'.repeat(80) + '\n');
178
+ }
179
+
180
+ /**
181
+ * Get optimization suggestions for slow components
182
+ */
183
+ _getSuggestions(componentName, renderTime) {
184
+ const suggestions = [
185
+ 'Reduce the amount of data rendered initially',
186
+ 'Use pagination or virtual scrolling for large lists',
187
+ 'Move expensive calculations to data fetching layer',
188
+ 'Consider lazy loading or code splitting',
189
+ 'Cache computed values',
190
+ 'Optimize database queries if data-fetching is involved'
191
+ ];
192
+
193
+ let details = `\nOptimization Suggestions:\n`;
194
+ suggestions.forEach((suggestion, index) => {
195
+ details += `${index + 1}. ${suggestion}\n`;
196
+ });
197
+
198
+ return details;
199
+ }
200
+
201
+ /**
202
+ * Get current metrics snapshot
203
+ */
204
+ getMetrics() {
205
+ return {
206
+ ...this.metrics,
207
+ currentTime: Date.now() - (this.metrics.totalStartTime || Date.now())
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Reset metrics
213
+ */
214
+ reset() {
215
+ this.metrics = {
216
+ totalStartTime: null,
217
+ totalEndTime: null,
218
+ components: new Map(),
219
+ slowComponents: [],
220
+ totalRenderTime: 0,
221
+ componentCount: 0
222
+ };
223
+ }
224
+ }
225
+
226
+ // Singleton instance
227
+ const monitor = new PerformanceMonitor();
228
+
229
+ module.exports = {
230
+ PerformanceMonitor,
231
+ monitor,
232
+ THRESHOLDS
233
+ };
@@ -0,0 +1,273 @@
1
+ /**
2
+ * SSRErrorHandler - Server-side rendering error handling
3
+ * Handles component render failures with graceful fallbacks
4
+ * Version: 1.0.0
5
+ */
6
+
7
+ const { MasterControllerError } = require('../MasterErrorHandler');
8
+
9
+ const isDevelopment = process.env.NODE_ENV !== 'production' && process.env.master === 'development';
10
+
11
+ /**
12
+ * Render error component for development mode
13
+ */
14
+ function renderErrorComponent(options = {}) {
15
+ const {
16
+ component,
17
+ error,
18
+ stack,
19
+ file,
20
+ line,
21
+ details
22
+ } = options;
23
+
24
+ const errorObj = new MasterControllerError({
25
+ code: 'MC_ERR_COMPONENT_RENDER_FAILED',
26
+ message: error || 'Component failed to render on server',
27
+ component,
28
+ file,
29
+ line,
30
+ details: details || stack,
31
+ originalError: options.originalError
32
+ });
33
+
34
+ // Return full HTML error page in development
35
+ return errorObj.toHTML();
36
+ }
37
+
38
+ /**
39
+ * Render fallback component for production mode
40
+ */
41
+ function renderFallback(componentName, options = {}) {
42
+ const { showSkeleton = true, customMessage } = options;
43
+
44
+ if (showSkeleton) {
45
+ return `
46
+ <div class="mc-fallback" data-component="${componentName}" style="
47
+ padding: 20px;
48
+ background: #f9fafb;
49
+ border-radius: 8px;
50
+ border: 1px dashed #d1d5db;
51
+ min-height: 100px;
52
+ display: flex;
53
+ align-items: center;
54
+ justify-content: center;
55
+ color: #6b7280;
56
+ ">
57
+ <div class="mc-fallback-content">
58
+ ${customMessage || ''}
59
+ <div class="skeleton-loader" style="
60
+ width: 100%;
61
+ height: 20px;
62
+ background: linear-gradient(90deg, #e5e7eb 25%, #f3f4f6 50%, #e5e7eb 75%);
63
+ background-size: 200% 100%;
64
+ animation: skeleton-loading 1.5s ease-in-out infinite;
65
+ border-radius: 4px;
66
+ "></div>
67
+ </div>
68
+ <style>
69
+ @keyframes skeleton-loading {
70
+ 0% { background-position: 200% 0; }
71
+ 100% { background-position: -200% 0; }
72
+ }
73
+ </style>
74
+ </div>
75
+ `;
76
+ }
77
+
78
+ // Minimal fallback - just an empty div
79
+ return `<div class="mc-fallback" data-component="${componentName}"></div>`;
80
+ }
81
+
82
+ /**
83
+ * Safe component render wrapper
84
+ * Catches errors and returns either error page (dev) or fallback (prod)
85
+ */
86
+ function safeRenderComponent(component, componentName, filePath) {
87
+ try {
88
+ // Try tempRender first
89
+ if (typeof component.tempRender === 'function') {
90
+ const startTime = Date.now();
91
+ const result = component.tempRender();
92
+ const renderTime = Date.now() - startTime;
93
+
94
+ // Warn about slow renders in development
95
+ if (isDevelopment && renderTime > 100) {
96
+ console.warn(
97
+ new MasterControllerError({
98
+ code: 'MC_ERR_SLOW_RENDER',
99
+ message: `Component rendering slowly on server (${renderTime}ms)`,
100
+ component: componentName,
101
+ file: filePath,
102
+ details: `Render time exceeded 100ms threshold. Consider optimizing this component.`
103
+ }).format()
104
+ );
105
+ }
106
+
107
+ return { success: true, html: result, renderTime };
108
+ }
109
+
110
+ // Fallback to connectedCallback
111
+ if (typeof component.connectedCallback === 'function') {
112
+ const startTime = Date.now();
113
+ component.connectedCallback();
114
+ const renderTime = Date.now() - startTime;
115
+
116
+ // Get the rendered HTML
117
+ const html = component.innerHTML || '';
118
+ return { success: true, html, renderTime };
119
+ }
120
+
121
+ // No render method found
122
+ throw new Error('No tempRender() or connectedCallback() method found');
123
+
124
+ } catch (error) {
125
+ console.error(
126
+ new MasterControllerError({
127
+ code: 'MC_ERR_COMPONENT_RENDER_FAILED',
128
+ message: `Failed to render component: ${error.message}`,
129
+ component: componentName,
130
+ file: filePath,
131
+ originalError: error
132
+ }).format()
133
+ );
134
+
135
+ if (isDevelopment) {
136
+ return {
137
+ success: false,
138
+ html: renderErrorComponent({
139
+ component: componentName,
140
+ error: error.message,
141
+ stack: error.stack,
142
+ file: filePath,
143
+ originalError: error
144
+ }),
145
+ renderTime: 0
146
+ };
147
+ } else {
148
+ // Log error for monitoring
149
+ logProductionError(error, componentName, filePath);
150
+
151
+ return {
152
+ success: false,
153
+ html: renderFallback(componentName, { showSkeleton: true }),
154
+ renderTime: 0
155
+ };
156
+ }
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Log production errors for monitoring
162
+ */
163
+ function logProductionError(error, component, file) {
164
+ const errorData = {
165
+ timestamp: new Date().toISOString(),
166
+ component,
167
+ file,
168
+ message: error.message,
169
+ stack: error.stack,
170
+ environment: 'production'
171
+ };
172
+
173
+ // Log to console (can be captured by monitoring services)
174
+ console.error('[MasterController Production Error]', JSON.stringify(errorData, null, 2));
175
+
176
+ // Hook for external logging services (Sentry, LogRocket, etc.)
177
+ if (global.masterControllerErrorHook) {
178
+ try {
179
+ global.masterControllerErrorHook(errorData);
180
+ } catch (hookError) {
181
+ console.error('[MasterController] Error hook failed:', hookError.message);
182
+ }
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Wrap connectedCallback with try-catch
188
+ */
189
+ function wrapConnectedCallback(element, componentName, filePath) {
190
+ if (!element || typeof element.connectedCallback !== 'function') {
191
+ return;
192
+ }
193
+
194
+ const originalCallback = element.connectedCallback;
195
+
196
+ element.connectedCallback = function(...args) {
197
+ try {
198
+ return originalCallback.apply(this, args);
199
+ } catch (error) {
200
+ console.error(
201
+ new MasterControllerError({
202
+ code: 'MC_ERR_COMPONENT_RENDER_FAILED',
203
+ message: `connectedCallback failed: ${error.message}`,
204
+ component: componentName,
205
+ file: filePath,
206
+ originalError: error
207
+ }).format()
208
+ );
209
+
210
+ if (isDevelopment) {
211
+ this.innerHTML = renderErrorComponent({
212
+ component: componentName,
213
+ error: error.message,
214
+ stack: error.stack,
215
+ file: filePath,
216
+ originalError: error
217
+ });
218
+ } else {
219
+ logProductionError(error, componentName, filePath);
220
+ this.innerHTML = renderFallback(componentName);
221
+ }
222
+ }
223
+ };
224
+ }
225
+
226
+ /**
227
+ * Check if component has required SSR methods
228
+ */
229
+ function validateSSRComponent(componentClass, componentName, filePath) {
230
+ const warnings = [];
231
+
232
+ // Check for tempRender method
233
+ if (!componentClass.prototype.tempRender && !componentClass.prototype.connectedCallback) {
234
+ warnings.push(
235
+ new MasterControllerError({
236
+ code: 'MC_ERR_TEMPRENDER_MISSING',
237
+ message: 'Component missing tempRender() method for SSR',
238
+ component: componentName,
239
+ file: filePath,
240
+ details: `Add a tempRender() method to enable server-side rendering:\n\n tempRender() {\n return \`<div>Your HTML here</div>\`;\n }`
241
+ })
242
+ );
243
+ }
244
+
245
+ // Warn if only render() exists (client-only)
246
+ if (componentClass.prototype.render && !componentClass.prototype.tempRender) {
247
+ warnings.push(
248
+ new MasterControllerError({
249
+ code: 'MC_ERR_TEMPRENDER_MISSING',
250
+ message: 'Component has render() but no tempRender() - will not SSR',
251
+ component: componentName,
252
+ file: filePath,
253
+ details: 'For SSR, rename render() to tempRender() or add a separate tempRender() method'
254
+ })
255
+ );
256
+ }
257
+
258
+ if (warnings.length > 0 && isDevelopment) {
259
+ warnings.forEach(warning => console.warn(warning.format()));
260
+ }
261
+
262
+ return warnings.length === 0;
263
+ }
264
+
265
+ module.exports = {
266
+ renderErrorComponent,
267
+ renderFallback,
268
+ safeRenderComponent,
269
+ wrapConnectedCallback,
270
+ validateSSRComponent,
271
+ logProductionError,
272
+ isDevelopment
273
+ };
@@ -0,0 +1,93 @@
1
+ /**
2
+ * MasterController Client-Side Hydration Runtime
3
+ * Handles error boundaries and hydration mismatch detection
4
+ * Version: 2.0.0
5
+ */
6
+
7
+ // Import error boundary
8
+ import { ErrorBoundary } from './ErrorBoundary.js';
9
+
10
+ // Import hydration mismatch detection
11
+ const isDevelopment = window.location.hostname === 'localhost' ||
12
+ window.location.hostname === '127.0.0.1';
13
+
14
+ if (isDevelopment && typeof require !== 'undefined') {
15
+ try {
16
+ const { enableHydrationMismatchDetection } = require('./HydrationMismatch.js');
17
+ enableHydrationMismatchDetection({
18
+ verbose: localStorage.getItem('mc-hydration-debug') === 'true',
19
+ delay: 1000
20
+ });
21
+ } catch (e) {
22
+ console.warn('[MasterController] Could not load hydration mismatch detection:', e.message);
23
+ }
24
+ }
25
+
26
+ // Auto-wrap app root with error boundary if not already wrapped
27
+ document.addEventListener('DOMContentLoaded', () => {
28
+ const appRoot = document.querySelector('root-layout') || document.body;
29
+
30
+ // Check if already wrapped
31
+ if (!appRoot.closest('error-boundary')) {
32
+ // Create error boundary wrapper
33
+ const boundary = document.createElement('error-boundary');
34
+
35
+ // Set development mode
36
+ if (isDevelopment) {
37
+ boundary.setAttribute('dev-mode', '');
38
+ }
39
+
40
+ // Configure custom error handler
41
+ boundary.onError = (errorInfo) => {
42
+ console.error('[App Error]', errorInfo);
43
+
44
+ // Send to monitoring service if configured
45
+ if (window.masterControllerErrorReporter) {
46
+ window.masterControllerErrorReporter(errorInfo);
47
+ }
48
+ };
49
+
50
+ // Wrap content
51
+ const parent = appRoot.parentNode;
52
+ parent.insertBefore(boundary, appRoot);
53
+ boundary.appendChild(appRoot);
54
+ }
55
+ });
56
+
57
+ // Global error reporter hook
58
+ window.masterControllerErrorReporter = window.masterControllerErrorReporter || function(errorData) {
59
+ console.log('[MasterController] Error reported:', errorData);
60
+
61
+ // Example: Send to your monitoring service
62
+ // fetch('/api/errors', {
63
+ // method: 'POST',
64
+ // headers: { 'Content-Type': 'application/json' },
65
+ // body: JSON.stringify(errorData)
66
+ // });
67
+
68
+ // Example: Send to Sentry
69
+ // if (window.Sentry) {
70
+ // Sentry.captureException(new Error(errorData.message), {
71
+ // extra: errorData
72
+ // });
73
+ // }
74
+ };
75
+
76
+ // Log successful hydration
77
+ if (isDevelopment) {
78
+ window.addEventListener('load', () => {
79
+ const ssrElements = document.querySelectorAll('[data-ssr]');
80
+ if (ssrElements.length > 0) {
81
+ console.log(
82
+ `%c✓ MasterController Hydration Complete`,
83
+ 'color: #10b981; font-weight: bold; font-size: 14px;'
84
+ );
85
+ console.log(` ${ssrElements.length} server-rendered components hydrated`);
86
+ }
87
+ });
88
+ }
89
+
90
+ // Export for manual use
91
+ export {
92
+ ErrorBoundary
93
+ };