mastercontroller 1.2.13 → 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.
Files changed (31) hide show
  1. package/.claude/settings.local.json +12 -0
  2. package/MasterAction.js +7 -7
  3. package/MasterControl.js +45 -22
  4. package/MasterHtml.js +5 -5
  5. package/MasterRouter.js +15 -7
  6. package/MasterTemplate.js +3 -3
  7. package/{MasterError.js → error/MasterError.js} +2 -2
  8. package/{MasterErrorLogger.js → error/MasterErrorLogger.js} +1 -1
  9. package/{MasterErrorMiddleware.js → error/MasterErrorMiddleware.js} +2 -2
  10. package/{ssr → error}/SSRErrorHandler.js +2 -2
  11. package/{MasterCache.js → monitoring/MasterCache.js} +2 -2
  12. package/{MasterMemoryMonitor.js → monitoring/MasterMemoryMonitor.js} +2 -2
  13. package/{MasterProfiler.js → monitoring/MasterProfiler.js} +2 -2
  14. package/{ssr → monitoring}/PerformanceMonitor.js +2 -2
  15. package/package.json +1 -1
  16. package/{EventHandlerValidator.js → security/EventHandlerValidator.js} +3 -3
  17. package/{MasterSanitizer.js → security/MasterSanitizer.js} +2 -2
  18. package/{MasterValidator.js → security/MasterValidator.js} +2 -2
  19. package/{SecurityMiddleware.js → security/SecurityMiddleware.js} +2 -2
  20. package/{SessionSecurity.js → security/SessionSecurity.js} +2 -2
  21. package/ssr/hydration-client.js +3 -3
  22. package/ssr/runtime-ssr.cjs +9 -9
  23. package/MasterBenchmark.js +0 -89
  24. package/MasterBuildOptimizer.js +0 -376
  25. package/MasterBundleAnalyzer.js +0 -108
  26. package/ssr/HTMLUtils.js +0 -15
  27. /package/{ssr → error}/ErrorBoundary.js +0 -0
  28. /package/{ssr → error}/HydrationMismatch.js +0 -0
  29. /package/{MasterBackendErrorHandler.js → error/MasterBackendErrorHandler.js} +0 -0
  30. /package/{MasterErrorHandler.js → error/MasterErrorHandler.js} +0 -0
  31. /package/{CSPConfig.js → security/CSPConfig.js} +0 -0
@@ -0,0 +1,12 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(rm:*)",
5
+ "Bash(mv:*)",
6
+ "Bash(node -e:*)",
7
+ "Bash(find:*)"
8
+ ],
9
+ "deny": [],
10
+ "ask": []
11
+ }
12
+ }
package/MasterAction.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- // version 0.0.22
2
+ // version 0.0.23
3
3
 
4
4
  var master = require('./MasterControl');
5
5
  var fileserver = require('fs');
@@ -16,14 +16,14 @@ var path = require('path');
16
16
  const compileWebComponentsHTML = require('./ssr/runtime-ssr.cjs');
17
17
 
18
18
  // Enhanced error handling
19
- const { handleTemplateError, sendErrorResponse } = require('./MasterBackendErrorHandler');
20
- const { safeReadFile } = require('./MasterErrorMiddleware');
21
- const { logger } = require('./MasterErrorLogger');
19
+ const { handleTemplateError, sendErrorResponse } = require('./error/MasterBackendErrorHandler');
20
+ const { safeReadFile } = require('./error/MasterErrorMiddleware');
21
+ const { logger } = require('./error/MasterErrorLogger');
22
22
 
23
23
  // Security - CSRF, validation, sanitization
24
- const { generateCSRFToken, validateCSRFToken } = require('./SecurityMiddleware');
25
- const { validator, validateRequestBody, sanitizeObject } = require('./MasterValidator');
26
- const { sanitizeUserHTML, escapeHTML } = require('./MasterSanitizer');
24
+ const { generateCSRFToken, validateCSRFToken } = require('./security/SecurityMiddleware');
25
+ const { validator, validateRequestBody, sanitizeObject } = require('./security/MasterValidator');
26
+ const { sanitizeUserHTML, escapeHTML } = require('./security/MasterSanitizer');
27
27
 
28
28
  class MasterAction{
29
29
 
package/MasterControl.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // MasterControl - by Alexander rich
2
- // version 1.0.248
2
+ // version 1.0.251
3
3
 
4
4
  var url = require('url');
5
5
  var fileserver = require('fs');
@@ -12,13 +12,13 @@ var path = require('path');
12
12
  var globSearch = require("glob");
13
13
 
14
14
  // Enhanced error handling - setup global handlers
15
- const { setupGlobalErrorHandlers } = require('./MasterErrorMiddleware');
16
- const { logger } = require('./MasterErrorLogger');
15
+ const { setupGlobalErrorHandlers } = require('./error/MasterErrorMiddleware');
16
+ const { logger } = require('./error/MasterErrorLogger');
17
17
 
18
18
  // Security - Initialize security features
19
- const { security, securityHeaders } = require('./SecurityMiddleware');
20
- const { csp } = require('./CSPConfig');
21
- const { session } = require('./SessionSecurity');
19
+ const { security, securityHeaders } = require('./security/SecurityMiddleware');
20
+ const { csp } = require('./security/CSPConfig');
21
+ const { session } = require('./security/SessionSecurity');
22
22
 
23
23
  // Initialize global error handling
24
24
  setupGlobalErrorHandlers();
@@ -193,23 +193,26 @@ class MasterControl {
193
193
  component(folderLocation, innerFolder){
194
194
 
195
195
  var rootFolderLocation = path.join(this.root, folderLocation, innerFolder);
196
- var files = globSearch.sync("**/*config.js", { cwd: rootFolderLocation, absolute: true });
197
- if(files && files.length > 0){
198
- require(files[0]);
196
+
197
+ // Structure is always: {rootFolderLocation}/config/initializers/config.js
198
+ var configPath = path.join(rootFolderLocation, 'config', 'initializers', 'config.js');
199
+ if(fs.existsSync(configPath)){
200
+ require(configPath);
199
201
  }else{
200
- this.error.log(`Cannot find config file under ${rootFolderLocation}`, "error");
202
+ this.error.log(`Cannot find config file at ${configPath}`, "error");
201
203
  }
202
- var routeFiles = globSearch.sync("**/*routes.js", { cwd: rootFolderLocation, absolute: true });
203
- var route = routeFiles && routeFiles.length > 0 ? routeFiles[0] : null;
204
+
205
+ // Structure is always: {rootFolderLocation}/config/routes.js
206
+ var routePath = path.join(rootFolderLocation, 'config', 'routes.js');
204
207
  var routeObject = {
205
- isComponent : true,
208
+ isComponent : true,
206
209
  root : rootFolderLocation
207
210
  }
208
211
  this.router.setup(routeObject);
209
- if(route){
210
- require(route);
212
+ if(fs.existsSync(routePath)){
213
+ require(routePath);
211
214
  }else{
212
- this.error.log(`Cannot find routes file under ${rootFolderLocation}`, "error");
215
+ this.error.log(`Cannot find routes file at ${routePath}`, "error");
213
216
  }
214
217
  }
215
218
 
@@ -541,16 +544,18 @@ class MasterControl {
541
544
 
542
545
  startMVC(foldername){
543
546
  var rootFolderLocation = path.join(this.root, foldername);
544
- var files = globSearch.sync("**/*routes.js", { cwd: rootFolderLocation, absolute: true });
547
+
548
+ // Structure is always: {rootFolderLocation}/routes.js
549
+ var routePath = path.join(rootFolderLocation, 'routes.js');
545
550
  var route = {
546
- isComponent : false,
551
+ isComponent : false,
547
552
  root : `${this.root}`
548
553
  }
549
554
  this.router.setup(route);
550
- if(files && files.length > 0){
551
- require(files[0]);
555
+ if(fs.existsSync(routePath)){
556
+ require(routePath);
552
557
  }else{
553
- this.error.log(`Cannot find routes file under ${rootFolderLocation}`, "error");
558
+ this.error.log(`Cannot find routes file at ${routePath}`, "error");
554
559
  }
555
560
  }
556
561
 
@@ -558,8 +563,26 @@ class MasterControl {
558
563
  // builds and calls all the required tools to have master running completely
559
564
  addInternalTools(requiredList){
560
565
  if(requiredList.constructor === Array){
566
+ // Map module names to their new organized paths
567
+ const modulePathMap = {
568
+ 'MasterError': './error/MasterError',
569
+ 'MasterAction': './MasterAction',
570
+ 'MasterActionFilters': './MasterActionFilters',
571
+ 'MasterRouter': './MasterRouter',
572
+ 'MasterRequest': './MasterRequest',
573
+ 'MasterCors': './MasterCors',
574
+ 'MasterSession': './MasterSession',
575
+ 'MasterSocket': './MasterSocket',
576
+ 'MasterHtml': './MasterHtml',
577
+ 'MasterTemplate': './MasterTemplate',
578
+ 'MasterTools': './MasterTools',
579
+ 'TemplateOverwrite': './TemplateOverwrite'
580
+ };
581
+
561
582
  for(var i = 0; i < requiredList.length; i++){
562
- require('./' + requiredList[i]);
583
+ const moduleName = requiredList[i];
584
+ const modulePath = modulePathMap[moduleName] || './' + moduleName;
585
+ require(modulePath);
563
586
  }
564
587
  }
565
588
  }
package/MasterHtml.js CHANGED
@@ -1,4 +1,4 @@
1
- // version 0.0.24
1
+ // version 0.0.25
2
2
 
3
3
  var master = require('./MasterControl');
4
4
  var fs = require('fs');
@@ -8,12 +8,12 @@ var temp = new tempClass();
8
8
  var tools = new toolClass();
9
9
 
10
10
  // Enhanced error handling
11
- const { handleTemplateError } = require('./MasterBackendErrorHandler');
12
- const { safeReadFile, safeFileExists } = require('./MasterErrorMiddleware');
13
- const { logger } = require('./MasterErrorLogger');
11
+ const { handleTemplateError } = require('./error/MasterBackendErrorHandler');
12
+ const { safeReadFile, safeFileExists } = require('./error/MasterErrorMiddleware');
13
+ const { logger } = require('./error/MasterErrorLogger');
14
14
 
15
15
  // Security - Sanitization
16
- const { sanitizeTemplateHTML, sanitizeUserHTML, escapeHTML } = require('./MasterSanitizer');
16
+ const { sanitizeTemplateHTML, sanitizeUserHTML, escapeHTML } = require('./security/MasterSanitizer');
17
17
 
18
18
  class html {
19
19
 
package/MasterRouter.js CHANGED
@@ -1,4 +1,4 @@
1
- // version 0.0.249
1
+ // version 0.0.250
2
2
 
3
3
  var master = require('./MasterControl');
4
4
  var toolClass = require('./MasterTools');
@@ -8,13 +8,13 @@ var currentRoute = {};
8
8
  var tools = new toolClass();
9
9
 
10
10
  // Enhanced error handling
11
- const { handleRoutingError, handleControllerError, sendErrorResponse } = require('./MasterBackendErrorHandler');
12
- const { logger } = require('./MasterErrorLogger');
13
- const { performanceTracker, errorHandlerMiddleware } = require('./MasterErrorMiddleware');
11
+ const { handleRoutingError, handleControllerError, sendErrorResponse } = require('./error/MasterBackendErrorHandler');
12
+ const { logger } = require('./error/MasterErrorLogger');
13
+ const { performanceTracker, errorHandlerMiddleware } = require('./error/MasterErrorMiddleware');
14
14
 
15
15
  // Security - Input validation and sanitization
16
- const { validator, detectPathTraversal, detectSQLInjection, detectCommandInjection } = require('./MasterValidator');
17
- const { escapeHTML } = require('./MasterSanitizer');
16
+ const { validator, detectPathTraversal, detectSQLInjection, detectCommandInjection } = require('./security/MasterValidator');
17
+ const { escapeHTML } = require('./security/MasterSanitizer');
18
18
 
19
19
  const isDevelopment = process.env.NODE_ENV !== 'production' && process.env.master === 'development';
20
20
 
@@ -135,10 +135,16 @@ const isDevelopment = process.env.NODE_ENV !== 'production' && process.env.maste
135
135
  try {
136
136
  requestObject.toController = routeList[item].toController;
137
137
  requestObject.toAction = routeList[item].toAction;
138
- var pathObj = normalizePaths(requestObject.pathName, routeList[item].path, requestObject.params);
138
+
139
+ // FIX: Create a clean copy of params for each route test to prevent parameter pollution
140
+ // This prevents parameters from non-matching routes from accumulating in requestObject.params
141
+ var testParams = Object.assign({}, requestObject.params);
142
+ var pathObj = normalizePaths(requestObject.pathName, routeList[item].path, testParams);
139
143
 
140
144
  // if we find the route that matches the request
141
145
  if(pathObj.requestPath === pathObj.routePath && routeList[item].type === requestObject.type){
146
+ // Only commit the extracted params if this route actually matches
147
+ requestObject.params = testParams;
142
148
 
143
149
  // call Constraint
144
150
  if(typeof routeList[item].constraint === "function"){
@@ -197,6 +203,8 @@ const isDevelopment = process.env.NODE_ENV !== 'production' && process.env.maste
197
203
 
198
204
  if(pathObj.requestPath === pathObj.routePath && "options" ===requestObject.type.toLowerCase()){
199
205
  // this means that the request is correct but its an options request means its the browser checking to see if the request is allowed
206
+ // Commit the params for OPTIONS requests too
207
+ requestObject.params = testParams;
200
208
  requestObject.response.writeHead(200, {'Content-Type': 'application/json'});
201
209
  requestObject.response.end(JSON.stringify({"done": "true"}));
202
210
  return true;
package/MasterTemplate.js CHANGED
@@ -1,10 +1,10 @@
1
- // version 0.0.4
1
+ // version 0.0.5
2
2
  // https://github.com/WebReflection/backtick-template
3
3
  // https://stackoverflow.com/questions/29182244/convert-a-string-to-a-template-string
4
4
 
5
5
  // Security - Template injection prevention
6
- const { escapeHTML } = require('./MasterSanitizer');
7
- const { logger } = require('./MasterErrorLogger');
6
+ const { escapeHTML } = require('./security/MasterSanitizer');
7
+ const { logger } = require('./error/MasterErrorLogger');
8
8
 
9
9
  var replace = ''.replace;
10
10
 
@@ -1,6 +1,6 @@
1
1
 
2
- // version 1.0.20 - improved console/error logging with syntax error code frames
3
- var master = require('./MasterControl');
2
+ // version 1.0.21 - improved console/error logging with syntax error code frames
3
+ var master = require('../MasterControl');
4
4
  var winston = require('winston');
5
5
  var fileserver = require('fs');
6
6
  const { request } = require('http');
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * MasterErrorLogger - Error logging infrastructure
3
3
  * Supports multiple logging backends and monitoring service integration
4
- * Version: 1.0.0
4
+ * Version: 1.0.1
5
5
  */
6
6
 
7
7
  const fs = require('fs');
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * MasterErrorMiddleware - Request/Response error handling middleware
3
- * Version: 1.0.0
3
+ * Version: 1.0.1
4
4
  */
5
5
 
6
6
  const { handleControllerError, handleRoutingError, sendErrorResponse } = require('./MasterBackendErrorHandler');
@@ -23,7 +23,7 @@ function errorHandlerMiddleware(handler, controllerName, actionName) {
23
23
  // Log successful request in development
24
24
  if (isDevelopment) {
25
25
  const duration = Date.now() - startTime;
26
- logger.debug({
26
+ logger.info({
27
27
  code: 'MC_INFO_REQUEST_SUCCESS',
28
28
  message: `${controllerName}#${actionName} completed`,
29
29
  context: {
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * SSRErrorHandler - Server-side rendering error handling
3
3
  * Handles component render failures with graceful fallbacks
4
- * Version: 1.0.0
4
+ * Version: 1.0.1
5
5
  */
6
6
 
7
- const { MasterControllerError } = require('../MasterErrorHandler');
7
+ const { MasterControllerError } = require('./MasterErrorHandler');
8
8
 
9
9
  const isDevelopment = process.env.NODE_ENV !== 'production' && process.env.master === 'development';
10
10
 
@@ -1,4 +1,4 @@
1
- // version 1.0.0
1
+ // version 1.0.1
2
2
  // MasterController Cache System - Runtime Performance Optimization
3
3
 
4
4
  /**
@@ -10,7 +10,7 @@
10
10
  * - TTL support
11
11
  */
12
12
 
13
- const { logger } = require('./MasterErrorLogger');
13
+ const { logger } = require('../error/MasterErrorLogger');
14
14
 
15
15
  /**
16
16
  * LRU Cache with TTL support
@@ -1,4 +1,4 @@
1
- // version 1.0.0
1
+ // version 1.0.1
2
2
  // MasterController Memory Monitor - Memory Leak Detection
3
3
 
4
4
  /**
@@ -9,7 +9,7 @@
9
9
  * - Memory alerts
10
10
  */
11
11
 
12
- const { logger } = require('./MasterErrorLogger');
12
+ const { logger } = require('../error/MasterErrorLogger');
13
13
 
14
14
  class MasterMemoryMonitor {
15
15
  constructor(options = {}) {
@@ -1,4 +1,4 @@
1
- // version 1.0.0
1
+ // version 1.0.1
2
2
  // MasterController Performance Profiler - Component and Request Profiling
3
3
 
4
4
  /**
@@ -10,7 +10,7 @@
10
10
  * - Detailed performance reports
11
11
  */
12
12
 
13
- const { logger } = require('./MasterErrorLogger');
13
+ const { logger } = require('../error/MasterErrorLogger');
14
14
 
15
15
  class MasterProfiler {
16
16
  constructor(options = {}) {
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * PerformanceMonitor - Track and report SSR performance metrics
3
- * Version: 1.0.0
3
+ * Version: 1.0.1
4
4
  */
5
5
 
6
- const { MasterControllerError } = require('../MasterErrorHandler');
6
+ const { MasterControllerError } = require('../error/MasterErrorHandler');
7
7
 
8
8
  const isDevelopment = process.env.NODE_ENV !== 'production' && process.env.master === 'development';
9
9
 
package/package.json CHANGED
@@ -18,5 +18,5 @@
18
18
  "scripts": {
19
19
  "test": "echo \"Error: no test specified\" && exit 1"
20
20
  },
21
- "version": "1.2.13"
21
+ "version": "1.2.14"
22
22
  }
@@ -1,4 +1,4 @@
1
- // version 1.0.0
1
+ // version 1.0.1
2
2
  // MasterController Event Handler Validator - Prevent code injection in @event attributes
3
3
 
4
4
  /**
@@ -8,8 +8,8 @@
8
8
  * - Malicious function calls
9
9
  */
10
10
 
11
- const { logger } = require('./MasterErrorLogger');
12
- const { MasterControllerError } = require('./MasterErrorHandler');
11
+ const { logger } = require('../error/MasterErrorLogger');
12
+ const { MasterControllerError } = require('../error/MasterErrorHandler');
13
13
 
14
14
  // Valid patterns for event handler expressions
15
15
  const VALID_PATTERNS = [
@@ -1,4 +1,4 @@
1
- // version 1.0.0
1
+ // version 1.0.1
2
2
  // MasterController HTML Sanitizer - XSS Protection
3
3
 
4
4
  /**
@@ -7,7 +7,7 @@
7
7
  * CSS injection, iframe attacks, form hijacking, meta tag injection
8
8
  */
9
9
 
10
- const { logger } = require('./MasterErrorLogger');
10
+ const { logger } = require('../error/MasterErrorLogger');
11
11
 
12
12
  // Dangerous HTML tags that should be removed
13
13
  const DANGEROUS_TAGS = [
@@ -1,4 +1,4 @@
1
- // version 1.0.0
1
+ // version 1.0.1
2
2
  // MasterController Input Validator - SQL Injection, Path Traversal, Command Injection Protection
3
3
 
4
4
  /**
@@ -12,7 +12,7 @@
12
12
  * - Header Injection
13
13
  */
14
14
 
15
- const { logger } = require('./MasterErrorLogger');
15
+ const { logger } = require('../error/MasterErrorLogger');
16
16
  const { escapeHTML } = require('./MasterSanitizer');
17
17
  const path = require('path');
18
18
 
@@ -1,4 +1,4 @@
1
- // version 1.0.0
1
+ // version 1.0.1
2
2
  // MasterController Security Middleware - CSRF, Headers, Rate Limiting, CORS
3
3
 
4
4
  /**
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  const crypto = require('crypto');
10
- const { logger } = require('./MasterErrorLogger');
10
+ const { logger } = require('../error/MasterErrorLogger');
11
11
 
12
12
  // Rate limiting store
13
13
  const rateLimitStore = new Map();
@@ -1,4 +1,4 @@
1
- // version 1.0.0
1
+ // version 1.0.1
2
2
  // MasterController Session Security - Secure cookie handling, session fixation prevention
3
3
 
4
4
  /**
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  const crypto = require('crypto');
10
- const { logger } = require('./MasterErrorLogger');
10
+ const { logger } = require('../error/MasterErrorLogger');
11
11
 
12
12
  // Session store (use Redis in production)
13
13
  const sessionStore = new Map();
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * MasterController Client-Side Hydration Runtime
3
3
  * Handles error boundaries and hydration mismatch detection
4
- * Version: 2.0.0
4
+ * Version: 2.0.1
5
5
  */
6
6
 
7
7
  // Import error boundary
8
- import { ErrorBoundary } from './ErrorBoundary.js';
8
+ import { ErrorBoundary } from '../error/ErrorBoundary.js';
9
9
 
10
10
  // Import hydration mismatch detection
11
11
  const isDevelopment = window.location.hostname === 'localhost' ||
@@ -13,7 +13,7 @@ const isDevelopment = window.location.hostname === 'localhost' ||
13
13
 
14
14
  if (isDevelopment && typeof require !== 'undefined') {
15
15
  try {
16
- const { enableHydrationMismatchDetection } = require('./HydrationMismatch.js');
16
+ const { enableHydrationMismatchDetection } = require('../error/HydrationMismatch.js');
17
17
  enableHydrationMismatchDetection({
18
18
  verbose: localStorage.getItem('mc-hydration-debug') === 'true',
19
19
  delay: 1000
@@ -13,18 +13,18 @@ const vm = require('vm');
13
13
  const moduleCache = new Map();
14
14
 
15
15
  // Error handling and monitoring
16
- const { MasterControllerError, findSimilarStrings } = require('../MasterErrorHandler');
17
- const { safeRenderComponent, validateSSRComponent, wrapConnectedCallback } = require('./SSRErrorHandler');
18
- const { monitor } = require('./PerformanceMonitor');
19
- const { logger } = require('../MasterErrorLogger');
16
+ const { MasterControllerError, findSimilarStrings } = require('../error/MasterErrorHandler');
17
+ const { safeRenderComponent, validateSSRComponent, wrapConnectedCallback } = require('../error/SSRErrorHandler');
18
+ const { monitor } = require('../monitoring/PerformanceMonitor');
19
+ const { logger } = require('../error/MasterErrorLogger');
20
20
 
21
21
  // Security - Sanitization and validation
22
- const { sanitizer, sanitizeTemplateHTML, sanitizeProps } = require('../MasterSanitizer');
23
- const { validateEventAttribute } = require('../EventHandlerValidator');
22
+ const { sanitizer, sanitizeTemplateHTML, sanitizeProps } = require('../security/MasterSanitizer');
23
+ const { validateEventAttribute } = require('../security/EventHandlerValidator');
24
24
 
25
25
  // Performance - Caching and profiling
26
- const { cache } = require('../MasterCache');
27
- const { profiler } = require('../MasterProfiler');
26
+ const { cache } = require('../monitoring/MasterCache');
27
+ const { profiler } = require('../monitoring/MasterProfiler');
28
28
 
29
29
  // Track registered custom elements to detect duplicates
30
30
  const registeredElements = new Map();
@@ -462,7 +462,7 @@ module.exports = async function compileWebComponentsHTML(inputHTML, preloadModul
462
462
  if (isDevelopment) {
463
463
  el.innerHTML = error.toHTML();
464
464
  } else {
465
- const { renderFallback } = require('./SSRErrorHandler');
465
+ const { renderFallback } = require('../error/SSRErrorHandler');
466
466
  el.innerHTML = renderFallback(componentName);
467
467
  }
468
468
  }
@@ -1,89 +0,0 @@
1
- // version 1.0.0
2
- // MasterController Benchmark - Performance Benchmarking
3
-
4
- const { profiler } = require('./MasterProfiler');
5
- const { logger } = require('./MasterErrorLogger');
6
-
7
- class MasterBenchmark {
8
- constructor() {
9
- this.results = [];
10
- }
11
-
12
- /**
13
- * Benchmark SSR render time
14
- */
15
- async benchmarkSSR(component, iterations = 100) {
16
- const times = [];
17
-
18
- for (let i = 0; i < iterations; i++) {
19
- const start = Date.now();
20
-
21
- // Render component (would call actual SSR here)
22
- await new Promise(resolve => setImmediate(resolve));
23
-
24
- const duration = Date.now() - start;
25
- times.push(duration);
26
- }
27
-
28
- return this.calculateStats(times, 'SSR Render');
29
- }
30
-
31
- /**
32
- * Benchmark hydration time
33
- */
34
- async benchmarkHydration(iterations = 100) {
35
- const times = [];
36
-
37
- for (let i = 0; i < iterations; i++) {
38
- const start = Date.now();
39
-
40
- // Simulate hydration
41
- await new Promise(resolve => setImmediate(resolve));
42
-
43
- const duration = Date.now() - start;
44
- times.push(duration);
45
- }
46
-
47
- return this.calculateStats(times, 'Hydration');
48
- }
49
-
50
- /**
51
- * Calculate statistics
52
- */
53
- calculateStats(times, name) {
54
- const sorted = times.sort((a, b) => a - b);
55
- const sum = times.reduce((a, b) => a + b, 0);
56
-
57
- return {
58
- name,
59
- iterations: times.length,
60
- min: sorted[0],
61
- max: sorted[sorted.length - 1],
62
- mean: sum / times.length,
63
- median: sorted[Math.floor(times.length / 2)],
64
- p95: sorted[Math.floor(times.length * 0.95)],
65
- p99: sorted[Math.floor(times.length * 0.99)]
66
- };
67
- }
68
-
69
- /**
70
- * Print benchmark results
71
- */
72
- printResults(stats) {
73
- console.log('\n═══════════════════════════════════════════════════');
74
- console.log('⚡ MasterController Benchmark Results');
75
- console.log('═══════════════════════════════════════════════════');
76
-
77
- console.log(`\n${stats.name} (${stats.iterations} iterations):`);
78
- console.log(` Mean: ${stats.mean.toFixed(2)}ms`);
79
- console.log(` Median: ${stats.median.toFixed(2)}ms`);
80
- console.log(` Min: ${stats.min.toFixed(2)}ms`);
81
- console.log(` Max: ${stats.max.toFixed(2)}ms`);
82
- console.log(` P95: ${stats.p95.toFixed(2)}ms`);
83
- console.log(` P99: ${stats.p99.toFixed(2)}ms`);
84
-
85
- console.log('═══════════════════════════════════════════════════\n');
86
- }
87
- }
88
-
89
- module.exports = { MasterBenchmark };
@@ -1,376 +0,0 @@
1
- // version 1.0.0
2
- // MasterController Build Optimizer - Minification, Tree Shaking, Dead Code Elimination
3
-
4
- /**
5
- * Build-time optimizations for MasterController
6
- * - Minifies event manifests
7
- * - Eliminates dead code
8
- * - Tree shaking for unused components
9
- * - Optimizes bundle size
10
- */
11
-
12
- const fs = require('fs');
13
- const path = require('path');
14
- const { logger } = require('./MasterErrorLogger');
15
-
16
- class MasterBuildOptimizer {
17
- constructor(options = {}) {
18
- this.rootDir = options.rootDir || process.cwd();
19
- this.outputDir = options.outputDir || path.join(this.rootDir, 'public', '__compiled__');
20
- this.minify = options.minify !== false;
21
- this.treeShake = options.treeShake !== false;
22
- this.deadCodeElimination = options.deadCodeElimination !== false;
23
- this.sourceMaps = options.sourceMaps || false;
24
-
25
- // Statistics
26
- this.stats = {
27
- filesProcessed: 0,
28
- bytesOriginal: 0,
29
- bytesOptimized: 0,
30
- timeTaken: 0,
31
- componentsFound: 0,
32
- componentsUsed: 0,
33
- componentsRemoved: 0
34
- };
35
- }
36
-
37
- /**
38
- * Optimize entire build
39
- */
40
- async optimize() {
41
- const startTime = Date.now();
42
-
43
- logger.info({
44
- code: 'MC_PERF_BUILD_START',
45
- message: 'Build optimization started'
46
- });
47
-
48
- try {
49
- // 1. Analyze component usage
50
- const usageMap = await this.analyzeComponentUsage();
51
-
52
- // 2. Tree shake unused components
53
- if (this.treeShake) {
54
- await this.treeShakeComponents(usageMap);
55
- }
56
-
57
- // 3. Minify event manifests
58
- if (this.minify) {
59
- await this.minifyEventManifests();
60
- }
61
-
62
- // 4. Eliminate dead code
63
- if (this.deadCodeElimination) {
64
- await this.eliminateDeadCode();
65
- }
66
-
67
- // 5. Optimize bundle
68
- await this.optimizeBundle();
69
-
70
- this.stats.timeTaken = Date.now() - startTime;
71
-
72
- // Log results
73
- this.logOptimizationResults();
74
-
75
- return this.stats;
76
- } catch (error) {
77
- logger.error({
78
- code: 'MC_PERF_BUILD_ERROR',
79
- message: 'Build optimization failed',
80
- error: error.message
81
- });
82
- throw error;
83
- }
84
- }
85
-
86
- /**
87
- * Analyze which components are actually used in the application
88
- */
89
- async analyzeComponentUsage() {
90
- const usageMap = new Map();
91
-
92
- // Scan all view files
93
- const viewsDir = path.join(this.rootDir, 'app', 'views');
94
- const viewFiles = this.findFiles(viewsDir, ['.html', '.js']);
95
-
96
- for (const file of viewFiles) {
97
- const content = fs.readFileSync(file, 'utf8');
98
-
99
- // Find custom element usages (<ui-button>, <ui-calendar>, etc.)
100
- const customElements = content.match(/<([a-z]+-[a-z-]+)/g) || [];
101
-
102
- for (const match of customElements) {
103
- const tagName = match.substring(1); // Remove <
104
- usageMap.set(tagName, (usageMap.get(tagName) || 0) + 1);
105
- }
106
- }
107
-
108
- this.stats.componentsFound = usageMap.size;
109
-
110
- logger.info({
111
- code: 'MC_PERF_USAGE_ANALYSIS',
112
- message: 'Component usage analysis complete',
113
- componentsFound: usageMap.size
114
- });
115
-
116
- return usageMap;
117
- }
118
-
119
- /**
120
- * Tree shake unused components from the bundle
121
- */
122
- async treeShakeComponents(usageMap) {
123
- const componentsDir = path.join(this.rootDir, 'app', 'assets', 'javascripts', 'shad-web-components', 'components');
124
-
125
- if (!fs.existsSync(componentsDir)) {
126
- return;
127
- }
128
-
129
- const componentFiles = this.findFiles(componentsDir, ['.js']);
130
- let removedCount = 0;
131
-
132
- for (const file of componentFiles) {
133
- const content = fs.readFileSync(file, 'utf8');
134
-
135
- // Extract component tag name from customElements.define call
136
- const defineMatch = content.match(/customElements\.define\(['"]([^'"]+)['"]/);
137
-
138
- if (defineMatch) {
139
- const tagName = defineMatch[1];
140
-
141
- // If component is not used, mark for removal
142
- if (!usageMap.has(tagName)) {
143
- removedCount++;
144
- logger.info({
145
- code: 'MC_PERF_TREE_SHAKE',
146
- message: `Unused component detected: ${tagName}`,
147
- file: path.basename(file)
148
- });
149
-
150
- // In production, we'd actually remove or exclude this from the bundle
151
- // For now, just log it
152
- }
153
- }
154
- }
155
-
156
- this.stats.componentsUsed = usageMap.size;
157
- this.stats.componentsRemoved = removedCount;
158
- }
159
-
160
- /**
161
- * Minify event manifest JSON files
162
- */
163
- async minifyEventManifests() {
164
- const manifestsDir = path.join(this.outputDir, 'event-manifests');
165
-
166
- if (!fs.existsSync(manifestsDir)) {
167
- return;
168
- }
169
-
170
- const manifestFiles = fs.readdirSync(manifestsDir).filter(f => f.endsWith('.json'));
171
-
172
- for (const file of manifestFiles) {
173
- const filePath = path.join(manifestsDir, file);
174
- const content = fs.readFileSync(filePath, 'utf8');
175
- const originalSize = Buffer.byteLength(content, 'utf8');
176
-
177
- // Parse and re-stringify without whitespace
178
- const parsed = JSON.parse(content);
179
- const minified = JSON.stringify(parsed);
180
-
181
- const minifiedSize = Buffer.byteLength(minified, 'utf8');
182
-
183
- // Write minified version
184
- fs.writeFileSync(filePath, minified, 'utf8');
185
-
186
- this.stats.filesProcessed++;
187
- this.stats.bytesOriginal += originalSize;
188
- this.stats.bytesOptimized += minifiedSize;
189
-
190
- logger.info({
191
- code: 'MC_PERF_MINIFY',
192
- message: `Minified ${file}`,
193
- originalSize: originalSize,
194
- minifiedSize: minifiedSize,
195
- savings: `${((1 - minifiedSize / originalSize) * 100).toFixed(1)}%`
196
- });
197
- }
198
- }
199
-
200
- /**
201
- * Eliminate dead code from JavaScript bundles
202
- */
203
- async eliminateDeadCode() {
204
- const jsDir = path.join(this.outputDir);
205
-
206
- if (!fs.existsSync(jsDir)) {
207
- return;
208
- }
209
-
210
- const jsFiles = fs.readdirSync(jsDir).filter(f => f.endsWith('.js'));
211
-
212
- for (const file of jsFiles) {
213
- const filePath = path.join(jsDir, file);
214
- let content = fs.readFileSync(filePath, 'utf8');
215
- const originalSize = Buffer.byteLength(content, 'utf8');
216
-
217
- // Remove console.log statements in production
218
- if (process.env.NODE_ENV === 'production') {
219
- content = content.replace(/console\.log\([^)]*\);?/g, '');
220
- content = content.replace(/console\.debug\([^)]*\);?/g, '');
221
- }
222
-
223
- // Remove comments
224
- content = content.replace(/\/\*[\s\S]*?\*\//g, ''); // Block comments
225
- content = content.replace(/\/\/.*/g, ''); // Line comments
226
-
227
- // Remove empty lines
228
- content = content.replace(/^\s*[\r\n]/gm, '');
229
-
230
- const optimizedSize = Buffer.byteLength(content, 'utf8');
231
-
232
- // Write optimized version
233
- fs.writeFileSync(filePath, content, 'utf8');
234
-
235
- this.stats.bytesOriginal += originalSize;
236
- this.stats.bytesOptimized += optimizedSize;
237
- }
238
- }
239
-
240
- /**
241
- * Optimize bundle size
242
- */
243
- async optimizeBundle() {
244
- // Analyze and report bundle sizes
245
- const compiledDir = this.outputDir;
246
-
247
- if (!fs.existsSync(compiledDir)) {
248
- return;
249
- }
250
-
251
- const files = fs.readdirSync(compiledDir);
252
- const bundles = [];
253
-
254
- for (const file of files) {
255
- const filePath = path.join(compiledDir, file);
256
- const stats = fs.statSync(filePath);
257
-
258
- if (stats.isFile() && file.endsWith('.js')) {
259
- bundles.push({
260
- name: file,
261
- size: stats.size,
262
- gzipSize: this.estimateGzipSize(stats.size)
263
- });
264
- }
265
- }
266
-
267
- // Sort by size
268
- bundles.sort((a, b) => b.size - a.size);
269
-
270
- // Log largest bundles
271
- const topBundles = bundles.slice(0, 5);
272
- for (const bundle of topBundles) {
273
- logger.info({
274
- code: 'MC_PERF_BUNDLE_SIZE',
275
- message: `Bundle: ${bundle.name}`,
276
- size: `${(bundle.size / 1024).toFixed(2)} KB`,
277
- gzipSize: `${(bundle.gzipSize / 1024).toFixed(2)} KB`
278
- });
279
- }
280
-
281
- return bundles;
282
- }
283
-
284
- /**
285
- * Estimate gzip size (approximation: ~30% of original)
286
- */
287
- estimateGzipSize(size) {
288
- return Math.round(size * 0.3);
289
- }
290
-
291
- /**
292
- * Find files recursively
293
- */
294
- findFiles(dir, extensions) {
295
- const files = [];
296
-
297
- if (!fs.existsSync(dir)) {
298
- return files;
299
- }
300
-
301
- const items = fs.readdirSync(dir);
302
-
303
- for (const item of items) {
304
- const fullPath = path.join(dir, item);
305
- const stat = fs.statSync(fullPath);
306
-
307
- if (stat.isDirectory()) {
308
- files.push(...this.findFiles(fullPath, extensions));
309
- } else if (extensions.some(ext => item.endsWith(ext))) {
310
- files.push(fullPath);
311
- }
312
- }
313
-
314
- return files;
315
- }
316
-
317
- /**
318
- * Log optimization results
319
- */
320
- logOptimizationResults() {
321
- const savingsPercent = this.stats.bytesOriginal > 0
322
- ? ((1 - this.stats.bytesOptimized / this.stats.bytesOriginal) * 100).toFixed(1)
323
- : 0;
324
-
325
- logger.info({
326
- code: 'MC_PERF_BUILD_COMPLETE',
327
- message: 'Build optimization complete',
328
- context: {
329
- filesProcessed: this.stats.filesProcessed,
330
- originalSize: `${(this.stats.bytesOriginal / 1024).toFixed(2)} KB`,
331
- optimizedSize: `${(this.stats.bytesOptimized / 1024).toFixed(2)} KB`,
332
- savings: `${savingsPercent}%`,
333
- timeTaken: `${this.stats.timeTaken}ms`,
334
- componentsFound: this.stats.componentsFound,
335
- componentsUsed: this.stats.componentsUsed,
336
- componentsRemoved: this.stats.componentsRemoved
337
- }
338
- });
339
-
340
- // Print summary
341
- console.log('\n═══════════════════════════════════════════════════');
342
- console.log('🚀 MasterController Build Optimization Complete');
343
- console.log('═══════════════════════════════════════════════════');
344
- console.log(`Files Processed: ${this.stats.filesProcessed}`);
345
- console.log(`Original Size: ${(this.stats.bytesOriginal / 1024).toFixed(2)} KB`);
346
- console.log(`Optimized Size: ${(this.stats.bytesOptimized / 1024).toFixed(2)} KB`);
347
- console.log(`Savings: ${savingsPercent}%`);
348
- console.log(`Time Taken: ${this.stats.timeTaken}ms`);
349
- console.log(`Components Found: ${this.stats.componentsFound}`);
350
- console.log(`Components Used: ${this.stats.componentsUsed}`);
351
- console.log(`Unused Components: ${this.stats.componentsRemoved}`);
352
- console.log('═══════════════════════════════════════════════════\n');
353
- }
354
- }
355
-
356
- // CLI usage
357
- if (require.main === module) {
358
- const optimizer = new MasterBuildOptimizer({
359
- rootDir: process.cwd(),
360
- minify: true,
361
- treeShake: true,
362
- deadCodeElimination: true
363
- });
364
-
365
- optimizer.optimize()
366
- .then(stats => {
367
- console.log('✅ Build optimization successful');
368
- process.exit(0);
369
- })
370
- .catch(error => {
371
- console.error('❌ Build optimization failed:', error.message);
372
- process.exit(1);
373
- });
374
- }
375
-
376
- module.exports = { MasterBuildOptimizer };
@@ -1,108 +0,0 @@
1
- // version 1.0.0
2
- // MasterController Bundle Analyzer - Bundle Size Analysis
3
-
4
- const fs = require('fs');
5
- const path = require('path');
6
- const { logger } = require('./MasterErrorLogger');
7
-
8
- class MasterBundleAnalyzer {
9
- constructor(options = {}) {
10
- this.rootDir = options.rootDir || process.cwd();
11
- this.outputDir = options.outputDir || path.join(this.rootDir, 'public', '__compiled__');
12
- }
13
-
14
- /**
15
- * Analyze bundles
16
- */
17
- analyze() {
18
- const bundles = this.getBundles();
19
- const report = this.generateReport(bundles);
20
-
21
- this.printReport(report);
22
-
23
- return report;
24
- }
25
-
26
- /**
27
- * Get all bundles
28
- */
29
- getBundles() {
30
- const bundles = [];
31
-
32
- if (!fs.existsSync(this.outputDir)) {
33
- return bundles;
34
- }
35
-
36
- const files = fs.readdirSync(this.outputDir);
37
-
38
- for (const file of files) {
39
- const filePath = path.join(this.outputDir, file);
40
- const stats = fs.statSync(filePath);
41
-
42
- if (stats.isFile() && file.endsWith('.js')) {
43
- bundles.push({
44
- name: file,
45
- size: stats.size,
46
- gzipSize: Math.round(stats.size * 0.3) // Estimate
47
- });
48
- }
49
- }
50
-
51
- return bundles.sort((a, b) => b.size - a.size);
52
- }
53
-
54
- /**
55
- * Generate report
56
- */
57
- generateReport(bundles) {
58
- const totalSize = bundles.reduce((sum, b) => sum + b.size, 0);
59
- const totalGzip = bundles.reduce((sum, b) => sum + b.gzipSize, 0);
60
-
61
- return {
62
- bundles,
63
- totalSize,
64
- totalGzip,
65
- bundleCount: bundles.length,
66
- averageSize: bundles.length > 0 ? totalSize / bundles.length : 0
67
- };
68
- }
69
-
70
- /**
71
- * Print report
72
- */
73
- printReport(report) {
74
- console.log('\n═══════════════════════════════════════════════════');
75
- console.log('📦 MasterController Bundle Analysis');
76
- console.log('═══════════════════════════════════════════════════');
77
-
78
- console.log(`\nTotal Bundles: ${report.bundleCount}`);
79
- console.log(`Total Size: ${(report.totalSize / 1024).toFixed(2)} KB`);
80
- console.log(`Total Size (Gzip): ${(report.totalGzip / 1024).toFixed(2)} KB`);
81
- console.log(`Average Bundle Size: ${(report.averageSize / 1024).toFixed(2)} KB`);
82
-
83
- console.log('\nLargest Bundles:');
84
- report.bundles.slice(0, 10).forEach((bundle, i) => {
85
- console.log(` ${i + 1}. ${bundle.name}`);
86
- console.log(` Size: ${(bundle.size / 1024).toFixed(2)} KB | Gzip: ${(bundle.gzipSize / 1024).toFixed(2)} KB`);
87
- });
88
-
89
- console.log('\n💡 Recommendations:');
90
- if (report.totalSize > 500000) {
91
- console.log(' ⚠️ Large total bundle size (>500KB)');
92
- console.log(' - Enable code splitting');
93
- console.log(' - Use dynamic imports');
94
- console.log(' - Tree shake unused code');
95
- }
96
-
97
- const largeBundles = report.bundles.filter(b => b.size > 100000);
98
- if (largeBundles.length > 0) {
99
- console.log(` ⚠️ ${largeBundles.length} bundles exceed 100KB`);
100
- console.log(' - Break into smaller chunks');
101
- console.log(' - Lazy load large components');
102
- }
103
-
104
- console.log('═══════════════════════════════════════════════════\n');
105
- }
106
- }
107
-
108
- module.exports = { MasterBundleAnalyzer };
package/ssr/HTMLUtils.js DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * Deprecated: HTMLUtils.js
3
- * Enhance SSR now compiles native web components directly to HTML.
4
- * This file remains as a no-op compatibility stub so any legacy references do not break.
5
- */
6
- class HTMLUtils {
7
- static escapeAttr(v) { return String(v ?? ''); }
8
- static unescapeAttr(v) { return v; }
9
- static encodeData(v) { return this.escapeAttr(v); }
10
- static decodeData(v) { return this.unescapeAttr(v); }
11
- static dataAttr(name, value) { return `${name}="${this.escapeAttr(value)}"`; }
12
- }
13
- if (typeof module !== 'undefined' && module.exports) module.exports = HTMLUtils;
14
- if (typeof window !== 'undefined') window.HTMLUtils = HTMLUtils;
15
- if (typeof exports !== 'undefined') exports.HTMLUtils = HTMLUtils;
File without changes
File without changes
File without changes