Skip to content

Commit 6ad1fe7

Browse files
authored
Merge pull request #13 from traceroot-ai/modify_config_loader
Modify config loader
2 parents fb5231d + eb763e0 commit 6ad1fe7

File tree

5 files changed

+520
-140
lines changed

5 files changed

+520
-140
lines changed

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "traceroot-sdk-ts",
3-
"version": "0.0.1-alpha.13",
3+
"version": "0.0.1-alpha.14",
44
"description": "TypeScript SDK for TraceRoot tracing and logging",
55
"main": "dist/index.js",
66
"types": "dist/index.d.ts",

src/utils/configLoader.ts

Lines changed: 90 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -111,128 +111,56 @@ export function findTypescriptConfig(): string | null {
111111

112112
console.log('[ConfigLoader] Looking for config files:', configNames);
113113

114-
// Strategy 1: Try current working directory
115-
console.log('[ConfigLoader] Strategy 1: Searching in current working directory');
114+
// Strategy 1: Try environment variables if available
115+
console.log('[ConfigLoader] Strategy 1: Checking environment variables');
116116
try {
117-
const currentPath = process.cwd();
118-
console.log('[ConfigLoader] Current working directory:', currentPath);
117+
const envConfigPath = process.env.TRACEROOT_CONFIG_PATH;
118+
console.log('[ConfigLoader] TRACEROOT_CONFIG_PATH environment variable:', envConfigPath);
119119

120-
if (currentPath && !currentPath.includes('ROOT/') && existsSync(currentPath)) {
121-
console.log('[ConfigLoader] Current directory exists and is valid');
122-
for (const configName of configNames) {
123-
const configPath = join(currentPath, configName);
124-
console.log('[ConfigLoader] Checking:', configPath);
125-
if (existsSync(configPath)) {
126-
console.log('[ConfigLoader] ✓ Found config file using Strategy 1:', configPath);
127-
return configPath;
128-
}
129-
}
130-
console.log('[ConfigLoader] Strategy 1: No config files found in current directory');
120+
if (envConfigPath && envConfigPath.trim() !== '' && existsSync(envConfigPath)) {
121+
console.log(
122+
'[ConfigLoader] ✓ Found config file using Strategy 1 (environment variable):',
123+
envConfigPath
124+
);
125+
return envConfigPath;
126+
} else if (envConfigPath && envConfigPath.trim() !== '') {
127+
console.log(
128+
'[ConfigLoader] Strategy 1: Environment variable set but file does not exist:',
129+
envConfigPath
130+
);
131131
} else {
132-
console.log('[ConfigLoader] Strategy 1: Current directory is invalid or contains ROOT/');
132+
console.log(
133+
'[ConfigLoader] Strategy 1: No TRACEROOT_CONFIG_PATH environment variable set or empty'
134+
);
133135
}
134136
} catch (error) {
135-
console.error('[ConfigLoader] Strategy 1 failed - process.cwd() error:', error);
136-
// process.cwd() might fail in some environments
137+
console.error('[ConfigLoader] Strategy 1 failed:', error);
137138
void error;
138139
}
139140

140-
// Strategy 2: Try relative to the module's location
141-
console.log('[ConfigLoader] Strategy 2: Searching relative to module location');
141+
// Strategy 2: Try current working directory
142+
console.log('[ConfigLoader] Strategy 2: Searching in current working directory');
142143
try {
143-
const moduleDir = __dirname;
144-
console.log('[ConfigLoader] Module directory:', moduleDir);
145-
let searchDir = moduleDir;
146-
147-
// Walk up the directory tree to find the project root
148-
for (let i = 0; i < 10; i++) {
149-
// Limit to prevent infinite loops
150-
console.log(
151-
'[ConfigLoader] Strategy 2 - Searching in directory (level',
152-
i + 1,
153-
'):',
154-
searchDir
155-
);
144+
const currentPath = process.cwd();
145+
console.log('[ConfigLoader] Current working directory:', currentPath);
156146

147+
if (currentPath && !currentPath.includes('ROOT/') && existsSync(currentPath)) {
148+
console.log('[ConfigLoader] Current directory exists and is valid');
157149
for (const configName of configNames) {
158-
const configPath = join(searchDir, configName);
150+
const configPath = join(currentPath, configName);
159151
console.log('[ConfigLoader] Checking:', configPath);
160152
if (existsSync(configPath)) {
161153
console.log('[ConfigLoader] ✓ Found config file using Strategy 2:', configPath);
162154
return configPath;
163155
}
164156
}
165-
166-
const parentDir = join(searchDir, '..');
167-
if (parentDir === searchDir) {
168-
console.log('[ConfigLoader] Strategy 2: Reached filesystem root, stopping search');
169-
break; // Reached filesystem root
170-
}
171-
searchDir = parentDir;
172-
}
173-
console.log('[ConfigLoader] Strategy 2: No config files found after walking up directory tree');
174-
} catch (error) {
175-
console.error('[ConfigLoader] Strategy 2 failed:', error);
176-
void error;
177-
}
178-
179-
// Strategy 3: Try common project locations relative to node_modules
180-
console.log('[ConfigLoader] Strategy 3: Searching relative to node_modules');
181-
try {
182-
const moduleLocation = require.resolve('traceroot-sdk-ts/package.json');
183-
console.log('[ConfigLoader] Module location:', moduleLocation);
184-
const nodeModulesIndex = moduleLocation.indexOf('node_modules');
185-
console.log('[ConfigLoader] node_modules index:', nodeModulesIndex);
186-
187-
if (nodeModulesIndex !== -1) {
188-
const projectRoot = moduleLocation.substring(0, nodeModulesIndex);
189-
console.log('[ConfigLoader] Inferred project root:', projectRoot);
190-
191-
if (existsSync(projectRoot)) {
192-
console.log('[ConfigLoader] Project root exists, searching for config files');
193-
for (const configName of configNames) {
194-
const configPath = join(projectRoot, configName);
195-
console.log('[ConfigLoader] Checking:', configPath);
196-
if (existsSync(configPath)) {
197-
console.log('[ConfigLoader] ✓ Found config file using Strategy 3:', configPath);
198-
return configPath;
199-
}
200-
}
201-
console.log('[ConfigLoader] Strategy 3: No config files found in project root');
202-
} else {
203-
console.log('[ConfigLoader] Strategy 3: Project root does not exist');
204-
}
157+
console.log('[ConfigLoader] Strategy 2: No config files found in current directory');
205158
} else {
206-
console.log('[ConfigLoader] Strategy 3: node_modules not found in module location');
159+
console.log('[ConfigLoader] Strategy 2: Current directory is invalid or contains ROOT/');
207160
}
208161
} catch (error) {
209-
console.error('[ConfigLoader] Strategy 3 failed - package.json resolution error:', error);
210-
// This might fail if package.json can't be resolved
211-
void error;
212-
}
213-
214-
// Strategy 4: Try environment variables if available
215-
console.log('[ConfigLoader] Strategy 4: Checking environment variables');
216-
try {
217-
const envConfigPath = process.env.TRACEROOT_CONFIG_PATH;
218-
console.log('[ConfigLoader] TRACEROOT_CONFIG_PATH environment variable:', envConfigPath);
219-
220-
if (envConfigPath && existsSync(envConfigPath)) {
221-
console.log(
222-
'[ConfigLoader] ✓ Found config file using Strategy 4 (environment variable):',
223-
envConfigPath
224-
);
225-
return envConfigPath;
226-
} else if (envConfigPath) {
227-
console.log(
228-
'[ConfigLoader] Strategy 4: Environment variable set but file does not exist:',
229-
envConfigPath
230-
);
231-
} else {
232-
console.log('[ConfigLoader] Strategy 4: No TRACEROOT_CONFIG_PATH environment variable set');
233-
}
234-
} catch (error) {
235-
console.error('[ConfigLoader] Strategy 4 failed:', error);
162+
console.error('[ConfigLoader] Strategy 2 failed - process.cwd() error:', error);
163+
// process.cwd() might fail in some environments
236164
void error;
237165
}
238166

@@ -360,51 +288,76 @@ function loadTypeScriptManually(configPath: string): TraceRootConfigFile | null
360288
/**
361289
* Helper function to try loading JavaScript config alternatives
362290
*/
363-
function tryJavaScriptFallback(): TraceRootConfigFile | null {
291+
export function tryJavaScriptFallback(): TraceRootConfigFile | null {
292+
// Strategy 1: Try environment variable first
293+
try {
294+
const envConfigPath = process.env.TRACEROOT_CONFIG_PATH;
295+
if (envConfigPath && envConfigPath.trim() !== '' && existsSync(envConfigPath)) {
296+
console.log('[ConfigLoader] Found config file from TRACEROOT_CONFIG_PATH:', envConfigPath);
297+
return loadJavaScriptConfig(envConfigPath);
298+
}
299+
} catch (error) {
300+
console.warn(`Failed to load config from TRACEROOT_CONFIG_PATH: ${error}`);
301+
}
302+
303+
// Strategy 2: Try current working directory
364304
const currentPath = process.cwd();
365305
const jsConfigNames = ['traceroot.config.js', 'traceroot.config.mjs', 'traceroot.config.cjs'];
366306

367307
for (const configName of jsConfigNames) {
368308
const configPath = join(currentPath, configName);
369309
if (existsSync(configPath)) {
370-
try {
371-
delete require.cache[configPath];
372-
373-
let configModule: any;
374-
375-
// Try multiple loading strategies for better compatibility
376-
try {
377-
// Strategy 1: Direct require with absolute path
378-
configModule = require(configPath);
379-
} catch (requireError) {
380-
void requireError;
381-
try {
382-
// Strategy 2: Try reading and evaluating the file manually
383-
const fs = require('fs');
384-
const fileContent = fs.readFileSync(configPath, 'utf8');
385-
const Module = require('module');
386-
const tempModule = new Module(configPath);
387-
tempModule.filename = configPath;
388-
tempModule.paths = Module._nodeModulePaths(require('path').dirname(configPath));
389-
tempModule._compile(fileContent, configPath);
390-
configModule = tempModule.exports;
391-
} catch (compileError) {
392-
throw compileError;
393-
}
394-
}
310+
const result = loadJavaScriptConfig(configPath);
311+
if (result) {
312+
return result;
313+
}
314+
}
315+
}
316+
return null;
317+
}
395318

396-
const config = configModule.default || configModule.config || configModule;
319+
/**
320+
* Helper function to load a JavaScript config file
321+
*/
322+
function loadJavaScriptConfig(configPath: string): TraceRootConfigFile | null {
323+
try {
324+
// Clear cache for both relative and absolute paths
325+
const absolutePath = require('path').resolve(configPath);
326+
delete require.cache[configPath];
327+
delete require.cache[absolutePath];
397328

398-
if (typeof config === 'function') {
399-
return config();
400-
}
329+
let configModule: any;
401330

402-
return config as TraceRootConfigFile;
403-
} catch (error) {
404-
console.warn(`Failed to load JavaScript config ${configPath}: ${error}`);
405-
continue;
331+
// Always use manual file reading to avoid Node.js module cache issues in tests
332+
// This ensures we read the latest content from disk
333+
try {
334+
const fs = require('fs');
335+
const fileContent = fs.readFileSync(absolutePath, 'utf8');
336+
const Module = require('module');
337+
const tempModule = new Module(absolutePath);
338+
tempModule.filename = absolutePath;
339+
tempModule.paths = Module._nodeModulePaths(require('path').dirname(absolutePath));
340+
tempModule._compile(fileContent, absolutePath);
341+
configModule = tempModule.exports;
342+
} catch (manualError) {
343+
void manualError;
344+
// Fallback to standard require if manual loading fails
345+
try {
346+
configModule = require(absolutePath);
347+
} catch (requireError) {
348+
throw requireError;
406349
}
407350
}
351+
352+
const config = configModule.default || configModule.config || configModule;
353+
354+
if (typeof config === 'function') {
355+
return config();
356+
}
357+
358+
return config as TraceRootConfigFile;
359+
} catch (error) {
360+
console.warn(`Failed to load JavaScript config ${configPath}: ${error}`);
361+
return null;
408362
}
409-
return null;
410363
}

0 commit comments

Comments
 (0)