Files
plan2code/src/installer/timing.js
T

71 lines
2.0 KiB
JavaScript
Raw Normal View History

'use strict';
const fs = require('fs');
const path = require('path');
function cleanFields(fields) {
const out = {};
for (const [key, value] of Object.entries(fields || {})) {
if (value !== undefined) out[key] = value;
}
return out;
}
function createTiming({ outputPath, ref, version, mode } = {}) {
const target = outputPath !== undefined ? outputPath : process.env.PLAN2CODE_BENCH_JSON || null;
const active = Boolean(target);
const base = cleanFields({ ref, version, mode });
function write(record) {
if (!active) return null;
try {
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.appendFileSync(target, `${JSON.stringify(record)}\n`, 'utf8');
return record;
} catch {
return null;
}
}
function timingEvent(name, extra = {}) {
if (!active || typeof name !== 'string' || !name) return null;
return write({ event: name, at: new Date().toISOString(), ...base, ...cleanFields(extra) });
}
function timingDuration(name, startMark, extra = {}) {
const durationMs = typeof startMark === 'number' ? Math.max(0, performance.now() - startMark) : 0;
return timingEvent(name, { ...extra, durationMs });
}
return { active, outputPath: target, timingEvent, timingDuration };
}
function timingEvent(name, extra = {}) {
return createTiming().timingEvent(name, extra);
}
function timingDuration(name, startMark, extra = {}) {
return createTiming().timingDuration(name, startMark, extra);
}
function readTimingEvents(file) {
let text;
try {
text = fs.readFileSync(file, 'utf8');
} catch {
return [];
}
const events = [];
for (const line of text.split(/\r?\n/)) {
if (!line.trim()) continue;
try {
const event = JSON.parse(line);
if (event && typeof event === 'object' && !Array.isArray(event)) events.push(event);
} catch {
// Malformed lines are ignored so one partial write does not hide later events.
}
}
return events;
}
module.exports = { createTiming, timingEvent, timingDuration, readTimingEvents };