code-graph-generator
Version:
Generate Json Object of code that can be used to generate code-graphs for JavaScript/TypeScript/Range projects
148 lines • 5.07 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logger = void 0;
exports.fileExists = fileExists;
exports.ensureDir = ensureDir;
exports.readFile = readFile;
const promises_1 = __importDefault(require("fs/promises"));
const fs_1 = require("fs");
const stream = __importStar(require("stream"));
const util_1 = require("util");
const ast_utils_1 = require("./ast-utils");
const pipeline = (0, util_1.promisify)(stream.pipeline);
const LARGE_FILE_THRESHOLD = 5 * 1024 * 1024; // 5MB
/**
* Checks if a file exists at the given path.
*/
async function fileExists(filePath) {
try {
await promises_1.default.access((0, ast_utils_1.normalizePath)(filePath));
return true;
}
catch {
return false;
}
}
/**
* Ensures a directory exists, creating it if necessary.
*/
async function ensureDir(dirPath) {
try {
await promises_1.default.mkdir((0, ast_utils_1.normalizePath)(dirPath), { recursive: true });
}
catch (error) {
// Only ignore EEXIST errors
if (error instanceof Error && 'code' in error && error.code !== 'EEXIST') {
throw error;
}
}
}
/**
* Reads a file with appropriate strategy based on size.
*/
async function readFile(filePath) {
const normalizedPath = (0, ast_utils_1.normalizePath)(filePath);
try {
const stats = await promises_1.default.stat(normalizedPath);
if (stats.size > LARGE_FILE_THRESHOLD) {
return readLargeFile(normalizedPath);
}
return promises_1.default.readFile(normalizedPath, 'utf-8');
}
catch (error) {
exports.logger.error(`Error reading file ${normalizedPath}:`, error);
throw error;
}
}
/**
* Reads a large file in chunks to avoid memory issues.
* Uses proper streaming to avoid loading the entire file into memory.
*/
async function readLargeFile(filePath) {
return new Promise((resolve, reject) => {
const chunks = [];
const readStream = (0, fs_1.createReadStream)(filePath, { encoding: 'utf8' });
readStream.on('data', (chunk) => {
// Add chunk directly, no need to convert if already buffer
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});
readStream.on('error', (err) => {
// Clean up
readStream.destroy();
reject(err);
});
readStream.on('end', () => {
// Clean up
readStream.destroy();
resolve(Buffer.concat(chunks).toString('utf-8'));
});
// Add timeout handling
const timeout = setTimeout(() => {
readStream.destroy();
reject(new Error(`Reading file ${filePath} timed out after 60s`));
}, 60000); // 60 second timeout
readStream.on('close', () => {
clearTimeout(timeout);
});
});
}
/**
* Logger utility with configurable debug level.
*/
exports.logger = {
debug: function (message, ...args) {
if (this._debug) {
console.debug(`[CodeGraph] ${message}`, ...args);
}
},
info: function (message, ...args) {
console.info(`[CodeGraph] ${message}`, ...args);
},
warn: function (message, ...args) {
console.warn(`[CodeGraph] ${message}`, ...args);
},
error: function (message, ...args) {
console.error(`[CodeGraph] ${message}`, ...args);
},
_debug: false,
setDebug: function (debug) {
this._debug = debug;
}
};
//# sourceMappingURL=file-utils.js.map