mastercontroller 1.3.6 โ†’ 1.3.8

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,273 @@
1
+ /**
2
+ * SSRErrorHandler - Server-side rendering error handling
3
+ * Handles component render failures with graceful fallbacks
4
+ * Version: 1.0.1
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,2 @@
1
+ {"timestamp":"2026-01-16T04:37:33.476Z","sessionId":"1768538253474-z0w973cmg","level":"INFO","code":"MC_INFO_FRAMEWORK_START","message":"MasterController framework initializing","component":null,"file":null,"line":null,"route":null,"context":{"version":"1.0.247","nodeVersion":"v20.19.4","platform":"darwin","env":"development"},"stack":null,"originalError":null,"environment":"development","nodeVersion":"v20.19.4","platform":"darwin","memory":{"rss":46104576,"heapTotal":10027008,"heapUsed":5720488,"external":2111800,"arrayBuffers":65875},"uptime":0.022275917}
2
+ {"timestamp":"2026-01-16T04:37:33.477Z","sessionId":"1768538253474-z0w973cmg","level":"INFO","code":"MC_INFO_SECURITY_INITIALIZED","message":"Security features initialized","component":null,"file":null,"line":null,"route":null,"context":{"environment":"development","features":{"securityHeaders":true,"csp":true,"csrf":true,"rateLimit":true,"sessionSecurity":true}},"stack":null,"originalError":null,"environment":"development","nodeVersion":"v20.19.4","platform":"darwin","memory":{"rss":46186496,"heapTotal":10027008,"heapUsed":5729744,"external":2111840,"arrayBuffers":65875},"uptime":0.022643334}
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "dependencies": {
3
- "qs" : "^6.14.1",
4
- "formidable": "^3.5.4",
3
+ "content-type": "^1.0.5",
5
4
  "cookie": "^1.1.1",
6
- "winston": "^3.19.0",
7
- "glob" :"^13.0.0"
5
+ "formidable": "^3.5.4",
6
+ "glob": "^13.0.0",
7
+ "qs": "^6.14.1",
8
+ "winston": "^3.19.0"
8
9
  },
9
10
  "description": "A class library that makes using the Master Framework a breeze",
10
11
  "homepage": "https://github.com/Tailor/MasterController#readme",
@@ -18,5 +19,5 @@
18
19
  "scripts": {
19
20
  "test": "echo \"Error: no test specified\" && exit 1"
20
21
  },
21
- "version": "1.3.6"
22
- }
22
+ "version": "1.3.8"
23
+ }
@@ -0,0 +1,76 @@
1
+ // Test for JSON parsing bug fix - empty body on GET requests
2
+
3
+ const http = require('http');
4
+ const EventEmitter = require('events');
5
+
6
+ console.log('๐Ÿงช Testing MasterRequest jsonStream with empty body...\n');
7
+
8
+ // Load MasterRequest
9
+ const { MasterRequest } = require('./MasterRequest');
10
+
11
+ // Create mock request with empty body (simulates GET request)
12
+ class MockRequest extends EventEmitter {
13
+ constructor() {
14
+ super();
15
+ this.headers = {
16
+ 'content-type': 'application/json'
17
+ };
18
+ }
19
+
20
+ simulateEmptyBody() {
21
+ // Simulate empty body - no data events, just end
22
+ setImmediate(() => {
23
+ this.emit('end');
24
+ });
25
+ }
26
+ }
27
+
28
+ // Test 1: Empty body should not throw error
29
+ console.log('Test 1: Empty body (GET request scenario)...');
30
+ const masterRequest1 = new MasterRequest();
31
+ masterRequest1.init({ maxJsonSize: 1024 * 1024 });
32
+ const mockReq1 = new MockRequest();
33
+
34
+ masterRequest1.jsonStream(mockReq1, (result) => {
35
+ if (result && typeof result === 'object' && !result.error) {
36
+ console.log('โœ… Empty body handled correctly');
37
+ console.log(' Result:', JSON.stringify(result));
38
+
39
+ // Test 2: Valid JSON body
40
+ console.log('\nTest 2: Valid JSON body...');
41
+ const masterRequest2 = new MasterRequest();
42
+ masterRequest2.init({ maxJsonSize: 1024 * 1024 });
43
+ const mockReq2 = new MockRequest();
44
+
45
+ masterRequest2.jsonStream(mockReq2, (result) => {
46
+ if (result && result.name === 'test' && result.value === 123) {
47
+ console.log('โœ… Valid JSON parsed correctly');
48
+ console.log(' Result:', JSON.stringify(result));
49
+
50
+ console.log('\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”');
51
+ console.log('โœจ ALL TESTS PASSED');
52
+ console.log('โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”');
53
+ console.log('\nFix verified:');
54
+ console.log('โœ… Empty body returns {} instead of throwing error');
55
+ console.log('โœ… Valid JSON still parses correctly');
56
+ console.log('โœ… No more "Unexpected end of JSON input" errors on GET requests');
57
+ } else {
58
+ console.log('โŒ Valid JSON parsing failed');
59
+ console.log(' Result:', JSON.stringify(result));
60
+ }
61
+ });
62
+
63
+ // Simulate valid JSON body
64
+ setImmediate(() => {
65
+ mockReq2.emit('data', Buffer.from('{"name":"test","value":123}'));
66
+ mockReq2.emit('end');
67
+ });
68
+
69
+ } else {
70
+ console.log('โŒ Empty body test failed');
71
+ console.log(' Result:', JSON.stringify(result));
72
+ }
73
+ });
74
+
75
+ // Start test
76
+ mockReq1.simulateEmptyBody();