@manojkmfsi/monodog 1.0.20 → 1.0.21

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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @manojkmfsi/monodog@1.0.20 build /home/runner/work/monodog/monodog/packages/monoapp
2
+ > @manojkmfsi/monodog@1.0.21 build /home/runner/work/monodog/monodog/packages/monoapp
3
3
  > rm -rf dist && tsc
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @manojkmfsi/monoapp
2
2
 
3
+ ## 1.0.21
4
+
5
+ ### Patch Changes
6
+
7
+ - updated security,workspce fallback, docs
8
+
3
9
  ## 1.0.20
4
10
 
5
11
  ### Patch Changes
@@ -39,7 +39,7 @@ const path = __importStar(require("path"));
39
39
  // Global variable to hold the loaded config
40
40
  let config = null;
41
41
  /**
42
- * Loads the monodog-conf.json file from the monorepo root.
42
+ * Loads the monodog-config.json file from the monorepo root.
43
43
  * This should be called only once during application startup.
44
44
  * @returns The application configuration object.
45
45
  */
@@ -50,8 +50,8 @@ function loadConfig() {
50
50
  // 1. Determine the path to the config file
51
51
  // We assume the backend package is running from the monorepo root (cwd is root)
52
52
  // or that we can navigate up to the root from the current file's location.
53
- const rootPath = path.resolve(process.cwd()); // Adjust based on your workspace folder depth from root if needed
54
- const configPath = path.resolve(rootPath, 'monodog-conf.json');
53
+ const rootPath = path.resolve(process.cwd());
54
+ const configPath = path.resolve(rootPath, 'monodog-config.json');
55
55
  createConfigFileIfMissing(rootPath);
56
56
  if (!fs.existsSync(configPath)) {
57
57
  console.error(`ERROR1: Configuration file not found at ${configPath}`);
@@ -61,21 +61,20 @@ function loadConfig() {
61
61
  // 2. Read and parse the JSON file
62
62
  const fileContent = fs.readFileSync(configPath, 'utf-8');
63
63
  const parsedConfig = JSON.parse(fileContent);
64
- // 3. Optional: Add validation logic here (e.g., check if ports are numbers)
65
64
  // Cache and return
66
65
  config = parsedConfig;
67
66
  process.stderr.write('[Config] Loaded configuration from: ...\n');
68
67
  return config;
69
68
  }
70
69
  catch (error) {
71
- console.error('ERROR: Failed to read or parse monodog-conf.json.');
70
+ console.error('ERROR: Failed to read or parse monodog-config.json.');
72
71
  console.error(error);
73
72
  process.exit(1);
74
73
  }
75
74
  }
76
75
  function createConfigFileIfMissing(rootPath) {
77
76
  // --- CONFIGURATION ---
78
- const configFileName = 'monodog-conf.json';
77
+ const configFileName = 'monodog-config.json';
79
78
  const configFilePath = path.resolve(rootPath, configFileName);
80
79
  // The default content for the configuration file
81
80
  const defaultContent = {
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const config_loader_1 = require("./config-loader");
4
4
  function generateUrl() {
5
- // const appConfig = loadConfig();
6
5
  const DATABASE_URL = `${config_loader_1.appConfig.database.path}`;
7
6
  process.env.DATABASE_URL = DATABASE_URL;
8
7
  process.stdout.write(DATABASE_URL);
package/dist/index.js CHANGED
@@ -9,94 +9,233 @@ const express_1 = __importDefault(require("express"));
9
9
  const cors_1 = __importDefault(require("cors"));
10
10
  const path_1 = __importDefault(require("path"));
11
11
  const body_parser_1 = require("body-parser");
12
+ const helmet_1 = __importDefault(require("helmet"));
12
13
  const config_loader_1 = require("./config-loader");
13
14
  const packageRoutes_1 = __importDefault(require("./routes/packageRoutes"));
14
15
  const commitRoutes_1 = __importDefault(require("./routes/commitRoutes"));
15
16
  const healthRoutes_1 = __importDefault(require("./routes/healthRoutes"));
16
17
  const configRoutes_1 = __importDefault(require("./routes/configRoutes"));
17
- // The main function exported and called by the CLI
18
- function startServer(rootPath, port, host) {
19
- const app = (0, express_1.default)();
20
- app.locals.rootPath = rootPath;
21
- // --- Middleware ---
22
- // 1. Logging Middleware
23
- app.use((_req, _res, next) => {
24
- console.log(`[SERVER] ${_req.method} ${_req.url} (Root: ${rootPath})`);
25
- next();
26
- });
27
- app.use((0, cors_1.default)());
28
- app.use((0, body_parser_1.json)());
29
- app.use('/api/packages', packageRoutes_1.default);
30
- // Get commit details
31
- app.use('/api/commits/', commitRoutes_1.default);
32
- // ---------- HEALTH --------------------
33
- app.use('/api/health/', healthRoutes_1.default);
34
- // ------------------------- CONFIGURATION TAB ------------------------- //
35
- // Get all configuration files from the file system
36
- app.use('/api/config/', configRoutes_1.default);
37
- // 404 handler
38
- app.use('*', (_, res) => {
39
- res.status(404).json({
40
- error: 'Endpoint not found',
41
- timestamp: Date.now(),
42
- });
18
+ // Security constants
19
+ const PORT_MIN = 1024;
20
+ const PORT_MAX = 65535;
21
+ // Validate port number
22
+ function validatePort(port) {
23
+ const portNum = typeof port === 'string' ? parseInt(port, 10) : port;
24
+ if (isNaN(portNum) || portNum < PORT_MIN || portNum > PORT_MAX) {
25
+ throw new Error(`Port must be between ${PORT_MIN} and ${PORT_MAX}`);
26
+ }
27
+ return portNum;
28
+ }
29
+ // Global error handler
30
+ const errorHandler = (err, req, res, _next) => {
31
+ const status = err.status || err.statusCode || 500;
32
+ const message = process.env.NODE_ENV === 'production'
33
+ ? 'Internal server error'
34
+ : err.message;
35
+ console.error('[ERROR]', {
36
+ status,
37
+ method: req.method,
38
+ path: req.path,
39
+ message: err.message,
43
40
  });
44
- const PORT = parseInt(port ? port.toString() : '4000');
45
- app
46
- .listen(PORT, host, async () => {
47
- console.log(`🚀 Backend server running on http://${host}:${PORT}`);
48
- console.log(`📊 API endpoints available:`);
49
- console.log(` - GET /api/health`);
50
- console.log(` - GET /api/packages/refresh`);
51
- console.log(` - GET /api/packages`);
52
- console.log(` - GET /api/packages/:name`);
53
- console.log(` - PUT /api/packages/update-config`);
54
- console.log(` - GET /api/commits/:packagePath`);
55
- console.log(` - GET /api/health/packages`);
56
- console.log(` - PUT /api/config/files/:id`);
57
- console.log(` - GET /api/config/files`);
58
- })
59
- .on('error', err => {
60
- // Handle common errors like EADDRINUSE (port already in use)
61
- if (err.message.includes('EADDRINUSE')) {
62
- console.error(`Error: Port ${port} is already in use. Please specify a different port via configuration file.`);
63
- process.exit(1);
64
- }
65
- else {
66
- console.error('Server failed to start:', err);
67
- process.exit(1);
68
- }
41
+ res.status(status).json({
42
+ error: 'Internal server error'
69
43
  });
44
+ };
45
+ // The main function exported and called by the CLI
46
+ function startServer(rootPath) {
47
+ try {
48
+ const port = config_loader_1.appConfig.server.port;
49
+ const host = config_loader_1.appConfig.server.host;
50
+ const validatedPort = validatePort(port);
51
+ const app = (0, express_1.default)();
52
+ // Set request timeout (30 seconds)
53
+ app.use((req, res, next) => {
54
+ req.setTimeout(30000);
55
+ res.setTimeout(30000);
56
+ next();
57
+ });
58
+ app.locals.rootPath = rootPath;
59
+ // Security middleware with CSP allowing API calls
60
+ const apiHost = host === '0.0.0.0' ? 'localhost' : host;
61
+ const apiUrl = process.env.API_URL || `http://${apiHost}:${validatedPort}`;
62
+ const dashboardHost = config_loader_1.appConfig.dashboard.host === '0.0.0.0' ? 'localhost' : config_loader_1.appConfig.dashboard.host;
63
+ const dashboardUrl = `http://${dashboardHost}:${config_loader_1.appConfig.dashboard.port}`;
64
+ app.use((0, helmet_1.default)({
65
+ contentSecurityPolicy: {
66
+ directives: {
67
+ defaultSrc: ["'self'"],
68
+ connectSrc: ["'self'", apiUrl, 'http://localhost:*', 'http://127.0.0.1:*'],
69
+ scriptSrc: ["'self'"],
70
+ imgSrc: ["'self'", 'data:', 'https:'],
71
+ },
72
+ },
73
+ }));
74
+ app.use((0, cors_1.default)({
75
+ origin: process.env.CORS_ORIGIN || dashboardUrl,
76
+ credentials: true,
77
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
78
+ allowedHeaders: ['Content-Type', 'Authorization'],
79
+ }));
80
+ app.use((0, body_parser_1.json)({ limit: '1mb' }));
81
+ // Request logging middleware (safe version)
82
+ app.use((_req, _res, next) => {
83
+ console.log(`[${new Date().toISOString()}] ${_req.method} ${_req.path}`);
84
+ next();
85
+ });
86
+ app.use('/api/packages', packageRoutes_1.default);
87
+ // Get commit details
88
+ app.use('/api/commits/', commitRoutes_1.default);
89
+ // Health check endpoint
90
+ app.use('/api/health/', healthRoutes_1.default);
91
+ // Configuration endpoint
92
+ app.use('/api/config/', configRoutes_1.default);
93
+ // 404 handler
94
+ app.use('*', (_, res) => {
95
+ res.status(404).json({
96
+ error: 'Endpoint not found',
97
+ timestamp: Date.now(),
98
+ });
99
+ });
100
+ // Global error handler (must be last)
101
+ app.use(errorHandler);
102
+ const server = app.listen(validatedPort, host, () => {
103
+ console.log(`🚀 Backend server running on http://${host}:${validatedPort}`);
104
+ console.log(`📊 API endpoints available:`);
105
+ console.log(` - GET /api/health`);
106
+ console.log(` - GET /api/packages/refresh`);
107
+ console.log(` - GET /api/packages`);
108
+ console.log(` - GET /api/packages/:name`);
109
+ console.log(` - PUT /api/packages/update-config`);
110
+ console.log(` - GET /api/commits/:packagePath`);
111
+ console.log(` - GET /api/health/packages`);
112
+ console.log(` - PUT /api/config/files/:id`);
113
+ console.log(` - GET /api/config/files`);
114
+ });
115
+ server.on('error', (err) => {
116
+ // Handle common errors like EADDRINUSE (port already in use)
117
+ if (err.code === 'EADDRINUSE') {
118
+ console.error(`Error: Port ${validatedPort} is already in use. Please specify a different port.`);
119
+ process.exit(1);
120
+ }
121
+ else if (err.code === 'EACCES') {
122
+ console.error(`Error: Permission denied to listen on port ${validatedPort}. Use a port above 1024.`);
123
+ process.exit(1);
124
+ }
125
+ else {
126
+ console.error('Server failed to start:', err.message);
127
+ process.exit(1);
128
+ }
129
+ });
130
+ // Graceful shutdown
131
+ process.on('SIGTERM', () => {
132
+ console.log('SIGTERM signal received: closing HTTP server');
133
+ server.close(() => {
134
+ console.log('HTTP server closed');
135
+ process.exit(0);
136
+ });
137
+ });
138
+ }
139
+ catch (error) {
140
+ console.error('Failed to start server:', error.message);
141
+ process.exit(1);
142
+ }
70
143
  }
71
- function serveDashboard(rootPath, port, host) {
72
- const app = (0, express_1.default)();
73
- app.get('/env-config.js', (req, res) => {
74
- res.setHeader('Content-Type', 'application/javascript');
75
- res.send(`window.ENV = { API_URL: "${`${config_loader_1.appConfig.server.host}:${config_loader_1.appConfig.server.port}` || 'localhost:8999'}" };`);
76
- });
77
- // This code makes sure that any request that does not matches a static file
78
- // in the build folder, will just serve index.html. Client side routing is
79
- // going to make sure that the correct content will be loaded.
80
- app.use((req, res, next) => {
81
- if (/(.ico|.js|.css|.jpg|.png|.map)$/i.test(req.path)) {
144
+ function serveDashboard(rootPath) {
145
+ try {
146
+ const port = config_loader_1.appConfig.dashboard.port;
147
+ const host = config_loader_1.appConfig.dashboard.host;
148
+ const validatedPort = validatePort(port);
149
+ const app = (0, express_1.default)();
150
+ // Security middleware
151
+ const serverHost = config_loader_1.appConfig.server.host === '0.0.0.0' ? 'localhost' : config_loader_1.appConfig.server.host;
152
+ const apiUrl = process.env.API_URL || `http://${serverHost}:${config_loader_1.appConfig.server.port}`;
153
+ app.use((0, helmet_1.default)({
154
+ contentSecurityPolicy: {
155
+ directives: {
156
+ defaultSrc: ["'self'"],
157
+ connectSrc: ["'self'", apiUrl, 'http://localhost:*', 'http://127.0.0.1:*'],
158
+ scriptSrc: ["'self'"],
159
+ imgSrc: ["'self'", 'data:', 'https:'],
160
+ },
161
+ },
162
+ }));
163
+ // Strict CORS for dashboard
164
+ app.use((0, cors_1.default)({
165
+ origin: false, // Don't allow any origin for static assets
166
+ }));
167
+ // Set request timeout
168
+ app.use((req, res, next) => {
169
+ req.setTimeout(30000);
170
+ res.setTimeout(30000);
82
171
  next();
83
- }
84
- else {
85
- res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
86
- res.header('Expires', '-1');
87
- res.header('Pragma', 'no-cache');
88
- res.sendFile('index.html', {
89
- root: path_1.default.resolve(__dirname, '..', 'monodog-dashboard', 'dist'),
172
+ });
173
+ app.get('/env-config.js', (req, res) => {
174
+ res.setHeader('Content-Type', 'application/javascript');
175
+ res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
176
+ const serverHost = config_loader_1.appConfig.server.host === '0.0.0.0' ? 'localhost' : config_loader_1.appConfig.server.host;
177
+ const apiUrl = process.env.API_URL || `http://${serverHost}:${config_loader_1.appConfig.server.port}`;
178
+ res.send(`window.ENV = { API_URL: "${apiUrl}" };`);
179
+ });
180
+ // This code makes sure that any request that does not matches a static file
181
+ // in the build folder, will just serve index.html. Client side routing is
182
+ // going to make sure that the correct content will be loaded.
183
+ app.use((req, res, next) => {
184
+ if (/(.ico|.js|.css|.jpg|.png|.map|.woff|.woff2|.ttf)$/i.test(req.path)) {
185
+ next();
186
+ }
187
+ else {
188
+ res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
189
+ res.header('Expires', '-1');
190
+ res.header('Pragma', 'no-cache');
191
+ res.sendFile('index.html', {
192
+ root: path_1.default.resolve(__dirname, '..', 'monodog-dashboard', 'dist'),
193
+ }, (err) => {
194
+ if (err) {
195
+ console.error('Error serving index.html:', err.message);
196
+ res.status(500).json({ error: 'Internal server error' });
197
+ }
198
+ });
199
+ }
200
+ });
201
+ const staticPath = path_1.default.join(__dirname, '..', 'monodog-dashboard', 'dist');
202
+ console.log('Serving static files from:', staticPath);
203
+ app.use(express_1.default.static(staticPath, {
204
+ maxAge: '1d',
205
+ etag: false,
206
+ dotfiles: 'deny', // Don't serve dot files
207
+ }));
208
+ // Global error handler
209
+ app.use(errorHandler);
210
+ const server = app.listen(validatedPort, host, () => {
211
+ console.log(`✅ Dashboard listening on http://${host}:${validatedPort}`);
212
+ console.log('Press Ctrl+C to quit.');
213
+ });
214
+ server.on('error', (err) => {
215
+ if (err.code === 'EADDRINUSE') {
216
+ console.error(`Error: Port ${validatedPort} is already in use.`);
217
+ process.exit(1);
218
+ }
219
+ else if (err.code === 'EACCES') {
220
+ console.error(`Error: Permission denied to listen on port ${validatedPort}.`);
221
+ process.exit(1);
222
+ }
223
+ else {
224
+ console.error('Server failed to start:', err.message);
225
+ process.exit(1);
226
+ }
227
+ });
228
+ // Graceful shutdown
229
+ process.on('SIGTERM', () => {
230
+ console.log('SIGTERM signal received: closing dashboard server');
231
+ server.close(() => {
232
+ console.log('Dashboard server closed');
233
+ process.exit(0);
90
234
  });
91
- }
92
- });
93
- const staticPath = path_1.default.join(__dirname, '..', 'monodog-dashboard', 'dist');
94
- console.log('Serving static files from:', staticPath);
95
- app.use(express_1.default.static(staticPath));
96
- // Start the server
97
- const PORT = parseInt(port ? port.toString() : '8999');
98
- app.listen(PORT, host, () => {
99
- console.log(`App listening on ${host}:${port}`);
100
- console.log('Press Ctrl+C to quit.');
101
- });
235
+ });
236
+ }
237
+ catch (error) {
238
+ console.error('Failed to start dashboard:', error.message);
239
+ process.exit(1);
240
+ }
102
241
  }
package/dist/serve.js CHANGED
@@ -2,102 +2,18 @@
2
2
  "use strict";
3
3
  /**
4
4
  * CLI Entry Point for serving Monodog.
5
- * * This script is executed when a user runs the serve command
5
+ * This script is executed when a user runs the serve command
6
6
  * in their project. It handles command-line arguments to determine
7
7
  * whether to:
8
8
  * 1. Start the API server for the dashboard.
9
9
  * 2. Start serving the dashboard frontend.
10
10
  */
11
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- var desc = Object.getOwnPropertyDescriptor(m, k);
14
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
- desc = { enumerable: true, get: function() { return m[k]; } };
16
- }
17
- Object.defineProperty(o, k2, desc);
18
- }) : (function(o, m, k, k2) {
19
- if (k2 === undefined) k2 = k;
20
- o[k2] = m[k];
21
- }));
22
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
- Object.defineProperty(o, "default", { enumerable: true, value: v });
24
- }) : function(o, v) {
25
- o["default"] = v;
26
- });
27
- var __importStar = (this && this.__importStar) || (function () {
28
- var ownKeys = function(o) {
29
- ownKeys = Object.getOwnPropertyNames || function (o) {
30
- var ar = [];
31
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
- return ar;
33
- };
34
- return ownKeys(o);
35
- };
36
- return function (mod) {
37
- if (mod && mod.__esModule) return mod;
38
- var result = {};
39
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
- __setModuleDefault(result, mod);
41
- return result;
42
- };
43
- })();
44
- var __importDefault = (this && this.__importDefault) || function (mod) {
45
- return (mod && mod.__esModule) ? mod : { "default": mod };
46
- };
47
11
  Object.defineProperty(exports, "__esModule", { value: true });
48
- const path = __importStar(require("path"));
49
- const index_1 = require("./index"); // Assume index.ts exports this function
50
- const config_loader_1 = require("./config-loader");
51
- const fs_1 = __importDefault(require("fs"));
52
- // --- Argument Parsing ---
53
- // 1. Get arguments excluding the node executable and script name
54
- const args = process.argv.slice(2);
55
- // Default settings
56
- const DEFAULT_PORT = 8999;
57
- const rootPath = findMonorepoRoot();
58
- const port = config_loader_1.appConfig.server.port ?? DEFAULT_PORT; //Default port
59
- const host = config_loader_1.appConfig.server.host ?? 'localhost'; //Default host
60
- // --- Execution Logic ---
12
+ const index_1 = require("./index");
13
+ const utilities_1 = require("./utils/utilities");
14
+ const rootPath = (0, utilities_1.findMonorepoRoot)();
61
15
  console.log(`Starting Monodog API server...`);
62
16
  console.log(`Analyzing monorepo at root: ${rootPath}`);
63
- // Start the Express server and begin analysis
64
- (0, index_1.startServer)(rootPath, port, host);
65
- (0, index_1.serveDashboard)(path.join(rootPath), config_loader_1.appConfig.dashboard.port, config_loader_1.appConfig.dashboard.host);
66
- /**
67
- * Find the monorepo root by looking for package.json with workspaces or pnpm-workspace.yaml
68
- */
69
- function findMonorepoRoot() {
70
- let currentDir = __dirname;
71
- while (currentDir !== path.parse(currentDir).root) {
72
- const packageJsonPath = path.join(currentDir, 'package.json');
73
- const pnpmWorkspacePath = path.join(currentDir, 'pnpm-workspace.yaml');
74
- // Check if this directory has package.json with workspaces or pnpm-workspace.yaml
75
- if (fs_1.default.existsSync(packageJsonPath)) {
76
- try {
77
- const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf8'));
78
- // If it has workspaces or is the root monorepo package
79
- if (packageJson.workspaces || fs_1.default.existsSync(pnpmWorkspacePath)) {
80
- console.log('✅ Found monorepo root:', currentDir);
81
- return currentDir;
82
- }
83
- }
84
- catch (error) {
85
- // Continue searching if package.json is invalid
86
- }
87
- }
88
- // Check if we're at the git root
89
- const gitPath = path.join(currentDir, '.git');
90
- if (fs_1.default.existsSync(gitPath)) {
91
- console.log('✅ Found git root (likely monorepo root):', currentDir);
92
- return currentDir;
93
- }
94
- // Go up one directory
95
- const parentDir = path.dirname(currentDir);
96
- if (parentDir === currentDir)
97
- break; // Prevent infinite loop
98
- currentDir = parentDir;
99
- }
100
- // Fallback to process.cwd() if we can't find the root
101
- console.log('⚠️ Could not find monorepo root, using process.cwd():', process.cwd());
102
- return process.cwd();
103
- }
17
+ // Start the Express server and dashboard
18
+ (0, index_1.startServer)(rootPath);
19
+ (0, index_1.serveDashboard)(rootPath);
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getCommitsByPathService = void 0;
7
- const gitService_1 = require("../gitService");
7
+ const gitService_1 = require("./gitService");
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const fs_1 = __importDefault(require("fs"));
10
10
  const getCommitsByPathService = async (packagePath) => {
@@ -32,107 +32,6 @@ const VALID_COMMIT_TYPES = [
32
32
  'build', // Build system changes (e.g., pnpm/npm scripts)
33
33
  'revert', // Reverting changes
34
34
  ];
35
- /**
36
- * The delimiter used to separate individual commit records in the git log output.
37
- * We use a unique string to ensure reliable splitting.
38
- */
39
- // const COMMIT_DELIMITER = '|---COMMIT-END---|';
40
- /**
41
- * The custom format string passed to 'git log'.
42
- * It uses JSON structure and our unique delimiter to make parsing consistent.
43
- * * %H: Commit hash
44
- * %pn: packageName name
45
- * %ae: Author email
46
- * %ad: Author date (ISO 8601 format)
47
- * %s: Subject (commit message's first line - used for 'message' and 'type' fields)
48
- */
49
- // const GIT_LOG_FORMAT = `{"hash": "%H", "author": "%ae", "packageName": "%pn", "date": "%ad", "message": "%s", "type": "%s"}${COMMIT_DELIMITER}`;
50
- // export class GitService {
51
- // private repoPath: string;
52
- // constructor(repoPath: string = process.cwd()) {
53
- // // Allows specifying a custom path to the monorepo root
54
- // this.repoPath = repoPath;
55
- // }
56
- // /**
57
- // * Retrieves commit history for the repository, optionally filtered by a package path.
58
- // * @param pathFilter The path to a package directory (e.g., 'packages/server').
59
- // * If provided, only commits affecting that path are returned.
60
- // * @returns A Promise resolving to an array of GitCommit objects.
61
- // */
62
- // public async getAllCommits(pathFilter?: string): Promise<GitCommit[]> {
63
- // const pathArgument = pathFilter ? ` -- ${pathFilter}` : '';
64
- // const command = `git log --pretty=format:'${GIT_LOG_FORMAT}' --date=iso-strict${pathArgument}`;
65
- // try {
66
- // console.log(`Executing Git command: ${command}`);
67
- // const { stdout } = await execPromise(command, {
68
- // cwd: this.repoPath,
69
- // maxBuffer: 1024 * 5000,
70
- // }); // Increase buffer for large repos
71
- // // console.log(stdout)
72
- // console.log(stdout, '--', this.repoPath);
73
- // const escapedDelimiter = COMMIT_DELIMITER.replace(
74
- // /[.*+?^${}()|[\]\\]/g,
75
- // '\\$&'
76
- // );
77
- // // 1. Remove the final trailing delimiter, as it creates an empty string at the end of the array
78
- // const cleanedOutput = stdout
79
- // .trim()
80
- // .replace(new RegExp(`${escapedDelimiter}$`), '');
81
- // console.log(cleanedOutput);
82
- // if (!cleanedOutput) {
83
- // return [];
84
- // }
85
- // // 2. Split the output by our custom delimiter to get an array of JSON strings
86
- // const jsonStrings = cleanedOutput.split(COMMIT_DELIMITER);
87
- // // 3. Parse each string into a GitCommit object
88
- // const commits: GitCommit[] = jsonStrings
89
- // .map(jsonString => {
90
- // try {
91
- // // JSON.parse is necessary because the output starts as a string
92
- // const commit = JSON.parse(jsonString);
93
- // console.log(commit.type, commit['hash']);
94
- // try {
95
- // // FIX: Updated Regex to handle optional scope (e.g., 'feat(scope):')
96
- // // Matches:
97
- // // 1. (^(\w+)) - The commit type (e.g., 'feat')
98
- // // 2. (\([^)]+\))? - The optional scope (e.g., '(setup)')
99
- // // 3. (:|!) - Ends with a colon or an exclamation point (for breaking changes)
100
- // const typeMatch = commit.type.match(/^(\w+)(\([^)]+\))?([:!])/);
101
- // let extractedType = 'other';
102
- // if (typeMatch) {
103
- // const rawType = typeMatch[1];
104
- // // NEW: Validate the extracted type against the list of known types
105
- // if (VALID_COMMIT_TYPES.includes(rawType)) {
106
- // extractedType = rawType;
107
- // }
108
- // }
109
- // commit.type = extractedType;
110
- // } catch (e) {
111
- // console.error('Failed to match commit type:', commit, e);
112
- // // Skip malformed entries
113
- // return null;
114
- // }
115
- // // // Set type to 'other' if the conventional format is not found
116
- // // commit.type = typeMatch ? typeMatch[1] : 'other';
117
- // return commit;
118
- // } catch (e) {
119
- // // console.log(jsonString)
120
- // console.error('Failed to parse commit JSON:', jsonString, e);
121
- // // Skip malformed entries
122
- // return null;
123
- // }
124
- // })
125
- // .filter((commit): commit is GitCommit => commit !== null);
126
- // return commits;
127
- // } catch (error) {
128
- // console.error('Error fetching Git history:', error);
129
- // // In a real application, you would handle this gracefully (e.g., throwing a custom error)
130
- // throw new Error(
131
- // 'Failed to retrieve Git commit history. Is Git installed and is the path correct?'
132
- // );
133
- // }
134
- // }
135
- // }
136
35
  class GitService {
137
36
  constructor(repoPath = process.cwd()) {
138
37
  this.repoPath = repoPath;