mastercontroller 1.2.12 → 1.2.14

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,265 @@
1
+ /**
2
+ * HydrationMismatch - Detect and report hydration mismatches
3
+ * Compares server-rendered HTML with client-rendered HTML
4
+ * Version: 1.0.0
5
+ */
6
+
7
+ const isDevelopment = typeof process !== 'undefined'
8
+ ? (process.env.NODE_ENV !== 'production')
9
+ : (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
10
+
11
+ /**
12
+ * Simple diff algorithm for HTML comparison
13
+ */
14
+ function generateDiff(serverHTML, clientHTML) {
15
+ const serverLines = serverHTML.split('\n').map(l => l.trim()).filter(Boolean);
16
+ const clientLines = clientHTML.split('\n').map(l => l.trim()).filter(Boolean);
17
+
18
+ const diff = [];
19
+ const maxLines = Math.max(serverLines.length, clientLines.length);
20
+
21
+ for (let i = 0; i < maxLines; i++) {
22
+ const serverLine = serverLines[i] || '';
23
+ const clientLine = clientLines[i] || '';
24
+
25
+ if (serverLine !== clientLine) {
26
+ diff.push({
27
+ line: i + 1,
28
+ server: serverLine,
29
+ client: clientLine,
30
+ type: !serverLine ? 'added' : !clientLine ? 'removed' : 'modified'
31
+ });
32
+ }
33
+ }
34
+
35
+ return diff;
36
+ }
37
+
38
+ /**
39
+ * Format diff for console output
40
+ */
41
+ function formatDiffForConsole(diff) {
42
+ let output = '\n';
43
+
44
+ diff.slice(0, 10).forEach(change => { // Show first 10 differences
45
+ output += `Line ${change.line}:\n`;
46
+
47
+ if (change.type === 'removed') {
48
+ output += ` \x1b[31m- ${change.server}\x1b[0m\n`;
49
+ } else if (change.type === 'added') {
50
+ output += ` \x1b[32m+ ${change.client}\x1b[0m\n`;
51
+ } else {
52
+ output += ` \x1b[31m- ${change.server}\x1b[0m\n`;
53
+ output += ` \x1b[32m+ ${change.client}\x1b[0m\n`;
54
+ }
55
+ });
56
+
57
+ if (diff.length > 10) {
58
+ output += `\n... and ${diff.length - 10} more differences\n`;
59
+ }
60
+
61
+ return output;
62
+ }
63
+
64
+ /**
65
+ * Compare attributes between two elements
66
+ */
67
+ function compareAttributes(serverEl, clientEl) {
68
+ const mismatches = [];
69
+
70
+ // Check server attributes
71
+ if (serverEl.attributes) {
72
+ for (const attr of serverEl.attributes) {
73
+ const serverValue = attr.value;
74
+ const clientValue = clientEl.getAttribute(attr.name);
75
+
76
+ if (serverValue !== clientValue) {
77
+ mismatches.push({
78
+ attribute: attr.name,
79
+ server: serverValue,
80
+ client: clientValue || '(missing)'
81
+ });
82
+ }
83
+ }
84
+ }
85
+
86
+ // Check for client attributes missing on server
87
+ if (clientEl.attributes) {
88
+ for (const attr of clientEl.attributes) {
89
+ if (!serverEl.hasAttribute(attr.name)) {
90
+ mismatches.push({
91
+ attribute: attr.name,
92
+ server: '(missing)',
93
+ client: attr.value
94
+ });
95
+ }
96
+ }
97
+ }
98
+
99
+ return mismatches;
100
+ }
101
+
102
+ /**
103
+ * Detect hydration mismatch between server and client HTML
104
+ */
105
+ function detectHydrationMismatch(element, componentName, options = {}) {
106
+ if (!element || !element.hasAttribute('data-ssr')) {
107
+ return null; // Not server-rendered
108
+ }
109
+
110
+ // Store server HTML before hydration
111
+ const serverHTML = element.innerHTML;
112
+
113
+ // Create a clone to test client rendering
114
+ const testElement = element.cloneNode(false);
115
+ testElement.removeAttribute('data-ssr');
116
+
117
+ // Simulate client render
118
+ if (typeof element.connectedCallback === 'function') {
119
+ try {
120
+ // Call connectedCallback to trigger client render
121
+ const originalCallback = element.constructor.prototype.connectedCallback;
122
+ if (originalCallback) {
123
+ originalCallback.call(testElement);
124
+ }
125
+ } catch (error) {
126
+ console.warn('[HydrationMismatch] Could not simulate client render:', error);
127
+ return null;
128
+ }
129
+ }
130
+
131
+ const clientHTML = testElement.innerHTML;
132
+
133
+ // Compare HTML
134
+ if (serverHTML.trim() === clientHTML.trim()) {
135
+ return null; // No mismatch
136
+ }
137
+
138
+ // Generate diff
139
+ const diff = generateDiff(serverHTML, clientHTML);
140
+
141
+ // Compare attributes
142
+ const attrMismatches = compareAttributes(element, testElement);
143
+
144
+ return {
145
+ component: componentName || element.tagName.toLowerCase(),
146
+ serverHTML,
147
+ clientHTML,
148
+ diff,
149
+ attrMismatches,
150
+ element
151
+ };
152
+ }
153
+
154
+ /**
155
+ * Report hydration mismatch to console
156
+ */
157
+ function reportHydrationMismatch(mismatch, options = {}) {
158
+ if (!mismatch) return;
159
+
160
+ const { component, diff, attrMismatches } = mismatch;
161
+
162
+ console.group('\x1b[33m⚠️ MasterController Hydration Mismatch\x1b[0m');
163
+ console.log(`\x1b[36mComponent:\x1b[0m ${component}`);
164
+
165
+ // Attribute mismatches
166
+ if (attrMismatches.length > 0) {
167
+ console.log('\n\x1b[33mAttribute Mismatches:\x1b[0m');
168
+ attrMismatches.forEach(attr => {
169
+ console.log(` ${attr.attribute}:`);
170
+ console.log(` \x1b[31mServer: ${attr.server}\x1b[0m`);
171
+ console.log(` \x1b[32mClient: ${attr.client}\x1b[0m`);
172
+ });
173
+ }
174
+
175
+ // HTML content mismatches
176
+ if (diff.length > 0) {
177
+ console.log('\n\x1b[33mHTML Diff:\x1b[0m');
178
+ console.log(formatDiffForConsole(diff));
179
+ }
180
+
181
+ // Suggestions
182
+ console.log('\n\x1b[36mPossible Causes:\x1b[0m');
183
+ console.log(' 1. Component state differs between server and client');
184
+ console.log(' 2. Conditional rendering based on client-only APIs (window, navigator, etc.)');
185
+ console.log(' 3. Missing or incorrect attributes in client-side render');
186
+ console.log(' 4. Random values or timestamps generated during render');
187
+ console.log(' 5. Missing data-ssr guard in connectedCallback');
188
+
189
+ console.log('\n\x1b[36mSuggestions:\x1b[0m');
190
+ console.log(' • Ensure server and client render with same props/state');
191
+ console.log(' • Use typeof window !== "undefined" checks for browser APIs');
192
+ console.log(' • Avoid random values or Date.now() in render logic');
193
+ console.log(' • Verify data-ssr attribute is present on server-rendered elements');
194
+
195
+ console.log('\n\x1b[34mLearn more:\x1b[0m https://mastercontroller.dev/docs/hydration#mismatches');
196
+ console.groupEnd();
197
+
198
+ // Log to monitoring service
199
+ if (typeof window !== 'undefined' && window.masterControllerErrorReporter) {
200
+ window.masterControllerErrorReporter({
201
+ type: 'hydration-mismatch',
202
+ component: mismatch.component,
203
+ diffCount: diff.length,
204
+ attrMismatchCount: attrMismatches.length
205
+ });
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Scan all SSR components for hydration mismatches
211
+ */
212
+ function scanForHydrationMismatches(options = {}) {
213
+ if (!isDevelopment) return;
214
+
215
+ const ssrElements = document.querySelectorAll('[data-ssr]');
216
+ const mismatches = [];
217
+
218
+ ssrElements.forEach(element => {
219
+ const componentName = element.tagName.toLowerCase();
220
+ const mismatch = detectHydrationMismatch(element, componentName, options);
221
+
222
+ if (mismatch) {
223
+ mismatches.push(mismatch);
224
+ reportHydrationMismatch(mismatch, options);
225
+ }
226
+ });
227
+
228
+ if (mismatches.length === 0 && options.verbose) {
229
+ console.log('\x1b[32m✓ No hydration mismatches detected\x1b[0m');
230
+ }
231
+
232
+ return mismatches;
233
+ }
234
+
235
+ /**
236
+ * Enable automatic hydration mismatch detection
237
+ */
238
+ function enableHydrationMismatchDetection(options = {}) {
239
+ if (!isDevelopment) return;
240
+
241
+ // Run check after hydration completes
242
+ if (typeof window !== 'undefined') {
243
+ window.addEventListener('load', () => {
244
+ setTimeout(() => {
245
+ scanForHydrationMismatches(options);
246
+ }, options.delay || 1000);
247
+ });
248
+ }
249
+ }
250
+
251
+ // Auto-enable in development
252
+ if (typeof window !== 'undefined' && isDevelopment) {
253
+ enableHydrationMismatchDetection({
254
+ verbose: localStorage.getItem('mc-hydration-debug') === 'true'
255
+ });
256
+ }
257
+
258
+ module.exports = {
259
+ detectHydrationMismatch,
260
+ reportHydrationMismatch,
261
+ scanForHydrationMismatches,
262
+ enableHydrationMismatchDetection,
263
+ generateDiff,
264
+ compareAttributes
265
+ };