tracenest-node 0.0.0-stage → 1.0.0
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.
- package/LICENSE +7 -0
- package/README.md +203 -2
- package/bin/tracenest.js +252 -0
- package/package.json +45 -3
- package/src/analysis/slowOperations.js +69 -0
- package/src/analysis/statistics.js +151 -0
- package/src/core/context.js +77 -0
- package/src/core/event.js +131 -0
- package/src/core/eventStore.js +151 -0
- package/src/core/operation.js +199 -0
- package/src/core/tracer.js +382 -0
- package/src/index.js +70 -0
- package/src/integrations/express.js +136 -0
- package/src/reporters/consoleReporter.js +167 -0
- package/src/reporters/jsonReporter.js +49 -0
- package/src/utils/formatting.js +66 -0
- package/src/utils/identifiers.js +30 -0
- package/src/utils/time.js +61 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
TraceNest License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Achintya Pandey
|
|
4
|
+
|
|
5
|
+
Permission is granted to any person obtaining a copy of this software and associated documentation files to deal in the Software without restriction, including rights to use, copy, modify, merge, publish, distribute, sublicense, and sell copies, subject to the condition that the above copyright notice and this permission notice appear in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
|
package/README.md
CHANGED
|
@@ -1,3 +1,204 @@
|
|
|
1
|
-
#
|
|
1
|
+
# TraceNest
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Lightweight, zero-dependency async execution tracing and hierarchical performance monitoring for Node.js applications.
|
|
4
|
+
|
|
5
|
+
TraceNest is a developer observability library built on Node.js native `AsyncLocalStorage`. It provides transparent tracking of asynchronous and synchronous execution flows, nested parent-child call hierarchies, latency bottlenecks, and error propagation without polluting your application logic.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Highlights
|
|
10
|
+
|
|
11
|
+
- **Zero External Dependencies**: Implemented purely with Node.js built-ins (`node:async_hooks`, `node:perf_hooks`, `node:crypto`).
|
|
12
|
+
- **Async Context Tracking**: Automatically links nested asynchronous calls across microtasks, timers, and I/O using `AsyncLocalStorage`.
|
|
13
|
+
- **Nested Hierarchies**: Automatically captures parent-child execution trees for database queries, external HTTP requests, and internal subroutines.
|
|
14
|
+
- **Microsecond Precision**: High-resolution operation duration calculations using `process.hrtime.bigint()`.
|
|
15
|
+
- **Error Preservation**: Intercepts and records thrown exceptions and stack traces while re-throwing them to preserve normal control flow.
|
|
16
|
+
- **Slow Operation Detection**: Configurable latency thresholds to pinpoint performance regressions.
|
|
17
|
+
- **Built-in CLI**: Terminal-based visualization of execution timelines, operation hierarchy trees, and performance metrics.
|
|
18
|
+
- **JSON Export**: Programmatic export of trace runs for archival, dashboards, or CI/CD test benchmarks.
|
|
19
|
+
- **Express Middleware**: Optional, non-intrusive HTTP middleware that nests all route activity beneath request-scoped traces.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install tracenest
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Requires Node.js `>= 20.0.0`.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Quick Start
|
|
34
|
+
|
|
35
|
+
```javascript
|
|
36
|
+
const TraceNest = require('tracenest');
|
|
37
|
+
|
|
38
|
+
// Start a tracing session
|
|
39
|
+
TraceNest.start({
|
|
40
|
+
name: 'BillingService',
|
|
41
|
+
slowOperationThresholdMs: 50
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// Trace a function (synchronous or asynchronous)
|
|
45
|
+
const result = await TraceNest.trace('Process Invoice', async () => {
|
|
46
|
+
TraceNest.track('Validating customer account');
|
|
47
|
+
|
|
48
|
+
await TraceNest.trace('Query Database', async () => {
|
|
49
|
+
// Database query logic here
|
|
50
|
+
await new Promise(resolve => setTimeout(resolve, 20));
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
return { status: 'PAID' };
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Print execution report to terminal
|
|
57
|
+
TraceNest.report();
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Core API Reference
|
|
63
|
+
|
|
64
|
+
### `TraceNest.start(options)`
|
|
65
|
+
Enables tracing and initializes a new trace session.
|
|
66
|
+
- `options.name` *(string)*: Descriptive service or session name. Default: `'default'`.
|
|
67
|
+
- `options.slowOperationThresholdMs` *(number)*: Threshold in ms to flag operations as slow. Default: `100`.
|
|
68
|
+
- `options.maxEvents` *(number)*: Maximum stored events before pruning oldest entries. Default: `10000`.
|
|
69
|
+
- `options.autoWarnSlowOperations` *(boolean)*: If true, emits a `WARNING` event when an operation exceeds threshold. Default: `false`.
|
|
70
|
+
|
|
71
|
+
### `TraceNest.stop()`
|
|
72
|
+
Temporarily halts recording of new events without discarding collected data.
|
|
73
|
+
|
|
74
|
+
### `TraceNest.reset()`
|
|
75
|
+
Disables tracing, clears stored events and operations, and resets the active session.
|
|
76
|
+
|
|
77
|
+
### `TraceNest.configure(options)`
|
|
78
|
+
Updates configuration parameters at runtime.
|
|
79
|
+
|
|
80
|
+
### `TraceNest.trace(name, fn, [metadata])`
|
|
81
|
+
Executes `fn` inside a monitored async context.
|
|
82
|
+
- Returns the return value of `fn` (or resolves the Promise).
|
|
83
|
+
- Preserves errors: if `fn` throws or rejects, the error is recorded on the operation and immediately re-thrown.
|
|
84
|
+
- Automatically creates parent-child relationships if invoked within another traced block.
|
|
85
|
+
|
|
86
|
+
### `TraceNest.begin(name, [metadata])`
|
|
87
|
+
Manually starts a timed operation. Returns an `Operation` instance:
|
|
88
|
+
- `operation.end([error])`: Marks the operation finished (or failed if an error is provided).
|
|
89
|
+
- `operation.fail(error)`: Explicitly fails the operation with an error.
|
|
90
|
+
- `operation.annotate(keyOrObject, [value])`: Attaches custom metadata.
|
|
91
|
+
- `operation.track(name, [metadata])`: Emits a point-in-time event under this operation.
|
|
92
|
+
|
|
93
|
+
### `TraceNest.track(name, [metadata])`
|
|
94
|
+
Records a point-in-time milestone event in the currently active execution context.
|
|
95
|
+
|
|
96
|
+
### `TraceNest.getActiveOperation()`
|
|
97
|
+
Returns the `Operation` currently executing in the active `AsyncLocalStorage` context, or `null`.
|
|
98
|
+
|
|
99
|
+
### `TraceNest.report([options])`
|
|
100
|
+
Renders and prints a formatted terminal report:
|
|
101
|
+
- `options.color` *(boolean)*: Enable or disable ANSI colors.
|
|
102
|
+
- `options.showTimeline` *(boolean)*: Include chronological event log. Default: `true`.
|
|
103
|
+
- `options.showTree` *(boolean)*: Include hierarchical operation tree. Default: `true`.
|
|
104
|
+
- `options.showSlow` *(boolean)*: Include slow operations section. Default: `true`.
|
|
105
|
+
- `options.silent` *(boolean)*: Return report string without printing to `console.log`.
|
|
106
|
+
|
|
107
|
+
### `TraceNest.exportJSON(filePath, [options])`
|
|
108
|
+
Exports structured trace data to a JSON file.
|
|
109
|
+
- Returns the resolved absolute file path.
|
|
110
|
+
|
|
111
|
+
### `TraceNest.getReportData([options])`
|
|
112
|
+
Returns an object containing raw trace statistics, operation lists, tree nodes, timeline events, and error details.
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## Express Integration
|
|
117
|
+
|
|
118
|
+
TraceNest provides optional middleware for Express-compatible web frameworks. It wraps each incoming request in an isolated async context so all downstream database queries, controller logic, and service calls automatically nest under the request:
|
|
119
|
+
|
|
120
|
+
```javascript
|
|
121
|
+
const express = require('express');
|
|
122
|
+
const TraceNest = require('tracenest');
|
|
123
|
+
|
|
124
|
+
const app = express();
|
|
125
|
+
|
|
126
|
+
TraceNest.start({ name: 'UserAPI', slowOperationThresholdMs: 100 });
|
|
127
|
+
|
|
128
|
+
// Mount TraceNest middleware
|
|
129
|
+
app.use(TraceNest.expressMiddleware({
|
|
130
|
+
ignorePaths: ['/health']
|
|
131
|
+
}));
|
|
132
|
+
|
|
133
|
+
app.get('/users/:id', async (req, res) => {
|
|
134
|
+
const user = await TraceNest.trace('Fetch User Profile', async () => {
|
|
135
|
+
return await TraceNest.trace('SQL: SELECT * FROM users', async () => {
|
|
136
|
+
return db.findUser(req.params.id);
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
res.json(user);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
app.listen(3000);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Middleware features:
|
|
147
|
+
- Automatically tags requests with an `x-request-id` header or generates a unique ID.
|
|
148
|
+
- Sets response headers `X-Trace-Id` and `X-Request-Id`.
|
|
149
|
+
- Captures HTTP status code, request method, route path, client IP, and latency.
|
|
150
|
+
- Flags HTTP `>= 400` responses as errors.
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## Command Line Interface (CLI)
|
|
155
|
+
|
|
156
|
+
TraceNest includes a command line utility to inspect trace files or run scripts with tracing enabled:
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
# View formatted report from an exported JSON trace
|
|
160
|
+
npx tracenest report ./trace.json
|
|
161
|
+
|
|
162
|
+
# Adjust slow operation threshold on the fly
|
|
163
|
+
npx tracenest report ./trace.json --threshold 50
|
|
164
|
+
|
|
165
|
+
# Output summary statistics only
|
|
166
|
+
npx tracenest summary ./trace.json
|
|
167
|
+
|
|
168
|
+
# Disable ANSI colors
|
|
169
|
+
npx tracenest report ./trace.json --no-color
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
## Performance Statistics
|
|
175
|
+
|
|
176
|
+
TraceNest computes the following metrics on every report:
|
|
177
|
+
- **Total Operations**: Number of tracked operations.
|
|
178
|
+
- **Success / Error Counts**: Status breakdown and success percentage.
|
|
179
|
+
- **Latency Distribution**: Minimum, maximum, average, and percentiles (P50, P90, P95, P99).
|
|
180
|
+
- **Slow Operations**: Operations matching or exceeding `slowOperationThresholdMs`.
|
|
181
|
+
- **Chronological Timeline**: Step-by-step event sequence with microsecond-level durations.
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## Verification & Testing
|
|
186
|
+
|
|
187
|
+
TraceNest comes with an automated test suite implemented with Node.js built-in runner (`node:test`):
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
# Run unit, integration, and concurrency tests
|
|
191
|
+
npm test
|
|
192
|
+
|
|
193
|
+
# Run example scripts
|
|
194
|
+
npm run example:basic
|
|
195
|
+
npm run example:nested
|
|
196
|
+
npm run example:express
|
|
197
|
+
npm run example:errors
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
---
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT (c) 2026 Achintya Pandey
|
package/bin/tracenest.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { fork } = require('node:child_process');
|
|
7
|
+
const pkg = require('../package.json');
|
|
8
|
+
const { ConsoleReporter } = require('../src/reporters/consoleReporter');
|
|
9
|
+
const { detectSlowOperations } = require('../src/analysis/slowOperations');
|
|
10
|
+
|
|
11
|
+
const args = process.argv.slice(2);
|
|
12
|
+
|
|
13
|
+
function printHelp() {
|
|
14
|
+
console.log(`
|
|
15
|
+
TraceNest CLI - v${pkg.version}
|
|
16
|
+
Usage:
|
|
17
|
+
tracenest <command> [options]
|
|
18
|
+
|
|
19
|
+
Commands:
|
|
20
|
+
report <file.json> Display formatted trace report from a JSON export
|
|
21
|
+
summary <file.json> Display concise summary statistics from a JSON export
|
|
22
|
+
run <script.js> [args...] Run a Node.js script with TraceNest auto-started and print report
|
|
23
|
+
version, --version, -v Show TraceNest version
|
|
24
|
+
help, --help, -h Show this help message
|
|
25
|
+
|
|
26
|
+
Options:
|
|
27
|
+
--threshold <ms> Custom slow operation threshold in milliseconds (default: 100)
|
|
28
|
+
--no-color Disable ANSI color formatting
|
|
29
|
+
--no-timeline Exclude chronological timeline from report
|
|
30
|
+
--no-tree Exclude hierarchical tree from report
|
|
31
|
+
--no-slow Exclude slow operations from report
|
|
32
|
+
--output <file.json> Save report to JSON file (used with run command)
|
|
33
|
+
|
|
34
|
+
Examples:
|
|
35
|
+
npx tracenest report ./trace-report.json
|
|
36
|
+
npx tracenest report ./trace-report.json --threshold 50
|
|
37
|
+
npx tracenest summary ./trace-report.json
|
|
38
|
+
npx tracenest run ./app.js --output trace.json
|
|
39
|
+
`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parseFlags(argList) {
|
|
43
|
+
const flags = {
|
|
44
|
+
color: true,
|
|
45
|
+
showTimeline: true,
|
|
46
|
+
showTree: true,
|
|
47
|
+
showSlow: true,
|
|
48
|
+
thresholdMs: undefined,
|
|
49
|
+
output: undefined
|
|
50
|
+
};
|
|
51
|
+
const positional = [];
|
|
52
|
+
|
|
53
|
+
for (let i = 0; i < argList.length; i++) {
|
|
54
|
+
const arg = argList[i];
|
|
55
|
+
if (arg === '--no-color') {
|
|
56
|
+
flags.color = false;
|
|
57
|
+
} else if (arg === '--no-timeline') {
|
|
58
|
+
flags.showTimeline = false;
|
|
59
|
+
} else if (arg === '--no-tree') {
|
|
60
|
+
flags.showTree = false;
|
|
61
|
+
} else if (arg === '--no-slow') {
|
|
62
|
+
flags.showSlow = false;
|
|
63
|
+
} else if (arg === '--threshold' && i + 1 < argList.length) {
|
|
64
|
+
flags.thresholdMs = parseFloat(argList[++i]);
|
|
65
|
+
} else if (arg.startsWith('--threshold=')) {
|
|
66
|
+
flags.thresholdMs = parseFloat(arg.split('=')[1]);
|
|
67
|
+
} else if (arg === '--output' && i + 1 < argList.length) {
|
|
68
|
+
flags.output = argList[++i];
|
|
69
|
+
} else if (arg.startsWith('--output=')) {
|
|
70
|
+
flags.output = arg.split('=')[1];
|
|
71
|
+
} else {
|
|
72
|
+
positional.push(arg);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return { flags, positional };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function loadJsonFile(filePath, commandName = 'report') {
|
|
80
|
+
if (!filePath) {
|
|
81
|
+
console.error(`
|
|
82
|
+
TraceNest CLI Error: Missing required trace file argument for '${commandName}'.
|
|
83
|
+
|
|
84
|
+
Usage:
|
|
85
|
+
npx tracenest ${commandName} <file.json> [options]
|
|
86
|
+
|
|
87
|
+
Examples:
|
|
88
|
+
npx tracenest ${commandName} ./trace-report.json
|
|
89
|
+
npx tracenest ${commandName} ./trace-report.json --threshold 50
|
|
90
|
+
|
|
91
|
+
To generate a trace report in your code:
|
|
92
|
+
const TraceNest = require('tracenest');
|
|
93
|
+
TraceNest.start();
|
|
94
|
+
// ... run traced operations ...
|
|
95
|
+
TraceNest.exportJSON('./trace-report.json');
|
|
96
|
+
`);
|
|
97
|
+
process.exit(1);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const resolved = path.resolve(process.cwd(), filePath);
|
|
101
|
+
if (!fs.existsSync(resolved)) {
|
|
102
|
+
console.error(`
|
|
103
|
+
TraceNest CLI Error: Trace file not found.
|
|
104
|
+
Path: ${resolved}
|
|
105
|
+
|
|
106
|
+
Please verify the file path exists and that TraceNest.exportJSON(...) generated the file.
|
|
107
|
+
`);
|
|
108
|
+
process.exit(1);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let raw;
|
|
112
|
+
try {
|
|
113
|
+
raw = fs.readFileSync(resolved, 'utf8');
|
|
114
|
+
} catch (err) {
|
|
115
|
+
console.error(`
|
|
116
|
+
TraceNest CLI Error: Unable to read trace file.
|
|
117
|
+
Path: ${resolved}
|
|
118
|
+
Error: ${err.message}
|
|
119
|
+
`);
|
|
120
|
+
process.exit(1);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
let parsed;
|
|
124
|
+
try {
|
|
125
|
+
parsed = JSON.parse(raw);
|
|
126
|
+
} catch (err) {
|
|
127
|
+
console.error(`
|
|
128
|
+
TraceNest CLI Error: Failed to parse trace file as valid JSON.
|
|
129
|
+
Path: ${resolved}
|
|
130
|
+
Syntax Error: ${err.message}
|
|
131
|
+
`);
|
|
132
|
+
process.exit(1);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Validate that the JSON structure represents a TraceNest trace
|
|
136
|
+
if (!parsed || typeof parsed !== 'object' || (!parsed.summary && !parsed.operations && !parsed.events)) {
|
|
137
|
+
console.error(`
|
|
138
|
+
TraceNest CLI Error: The file does not appear to be a valid TraceNest trace export.
|
|
139
|
+
Path: ${resolved}
|
|
140
|
+
Expected properties such as 'summary', 'operations', or 'events'.
|
|
141
|
+
`);
|
|
142
|
+
process.exit(1);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return parsed;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function handleReport(targetFile, flags) {
|
|
149
|
+
const data = loadJsonFile(targetFile, 'report');
|
|
150
|
+
|
|
151
|
+
// Recalculate slow operations if custom threshold was passed
|
|
152
|
+
if (typeof flags.thresholdMs === 'number' && data.operations) {
|
|
153
|
+
data.slowOperations = detectSlowOperations(data.operations, flags.thresholdMs);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const reporter = new ConsoleReporter();
|
|
157
|
+
reporter.print(data, {
|
|
158
|
+
color: flags.color,
|
|
159
|
+
showTimeline: flags.showTimeline,
|
|
160
|
+
showTree: flags.showTree,
|
|
161
|
+
showSlow: flags.showSlow
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function handleSummary(targetFile, flags) {
|
|
166
|
+
const data = loadJsonFile(targetFile, 'summary');
|
|
167
|
+
const reporter = new ConsoleReporter();
|
|
168
|
+
reporter.print(data, {
|
|
169
|
+
color: flags.color,
|
|
170
|
+
showTimeline: false,
|
|
171
|
+
showTree: false,
|
|
172
|
+
showSlow: false
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function handleRun(scriptPath, extraArgs, flags) {
|
|
177
|
+
if (!scriptPath) {
|
|
178
|
+
console.error(`
|
|
179
|
+
TraceNest CLI Error: Missing script path argument for 'run'.
|
|
180
|
+
|
|
181
|
+
Usage:
|
|
182
|
+
npx tracenest run <script.js> [args...] [--output <file.json>]
|
|
183
|
+
|
|
184
|
+
Example:
|
|
185
|
+
npx tracenest run ./app.js
|
|
186
|
+
npx tracenest run ./app.js --output trace.json
|
|
187
|
+
`);
|
|
188
|
+
process.exit(1);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const resolvedScript = path.resolve(process.cwd(), scriptPath);
|
|
192
|
+
if (!fs.existsSync(resolvedScript)) {
|
|
193
|
+
console.error(`
|
|
194
|
+
TraceNest CLI Error: Target script not found.
|
|
195
|
+
Path: ${resolvedScript}
|
|
196
|
+
`);
|
|
197
|
+
process.exit(1);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const child = fork(resolvedScript, extraArgs, {
|
|
201
|
+
stdio: 'inherit',
|
|
202
|
+
env: {
|
|
203
|
+
...process.env,
|
|
204
|
+
NODE_OPTIONS: `${process.env.NODE_OPTIONS || ''} --require ${path.resolve(__dirname, '../src/index.js')}`
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
child.on('exit', (code) => {
|
|
209
|
+
process.exit(code || 0);
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Main CLI dispatch
|
|
214
|
+
function main() {
|
|
215
|
+
if (args.length === 0 || args[0] === 'help' || args[0] === '--help' || args[0] === '-h') {
|
|
216
|
+
printHelp();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (args[0] === 'version' || args[0] === '--version' || args[0] === '-v') {
|
|
221
|
+
console.log(`TraceNest v${pkg.version}`);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const { flags, positional } = parseFlags(args);
|
|
226
|
+
const command = positional[0];
|
|
227
|
+
const target = positional[1];
|
|
228
|
+
|
|
229
|
+
switch (command) {
|
|
230
|
+
case 'report':
|
|
231
|
+
handleReport(target, flags);
|
|
232
|
+
break;
|
|
233
|
+
case 'summary':
|
|
234
|
+
handleSummary(target, flags);
|
|
235
|
+
break;
|
|
236
|
+
case 'run':
|
|
237
|
+
handleRun(target, positional.slice(2), flags);
|
|
238
|
+
break;
|
|
239
|
+
default:
|
|
240
|
+
// If the first argument is a JSON file directly: tracenest ./report.json
|
|
241
|
+
if (command && command.endsWith('.json')) {
|
|
242
|
+
handleReport(command, flags);
|
|
243
|
+
} else {
|
|
244
|
+
console.error(`Unknown command: ${command}`);
|
|
245
|
+
printHelp();
|
|
246
|
+
process.exit(1);
|
|
247
|
+
}
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tracenest-node",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Lightweight Node.js async execution tracing, nested operation monitoring, and performance analysis library",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"bin": {
|
|
7
|
+
"tracenest": "bin/tracenest.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"src",
|
|
11
|
+
"bin",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test tests/*.test.js",
|
|
17
|
+
"example:basic": "node examples/basic.js",
|
|
18
|
+
"example:nested": "node examples/nested.js",
|
|
19
|
+
"example:express": "node examples/express.js",
|
|
20
|
+
"example:errors": "node examples/error-handling.js"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"tracing",
|
|
24
|
+
"async-hooks",
|
|
25
|
+
"async-local-storage",
|
|
26
|
+
"performance",
|
|
27
|
+
"profiling",
|
|
28
|
+
"execution-flow",
|
|
29
|
+
"observability",
|
|
30
|
+
"nested-tracing",
|
|
31
|
+
"express-middleware",
|
|
32
|
+
"timeline",
|
|
33
|
+
"apm"
|
|
34
|
+
],
|
|
35
|
+
"author": "Achintya Pandey",
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=20.0.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"express": ">=4.0.0"
|
|
42
|
+
},
|
|
43
|
+
"peerDependenciesMeta": {
|
|
44
|
+
"express": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
}
|
|
6
48
|
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Detects operations that exceeded a duration threshold.
|
|
5
|
+
*
|
|
6
|
+
* @param {Array<import('../core/operation').Operation>} operations
|
|
7
|
+
* @param {number} [thresholdMs=100]
|
|
8
|
+
* @returns {Array<object>} sorted descending by duration
|
|
9
|
+
*/
|
|
10
|
+
function detectSlowOperations(operations = [], thresholdMs = 100) {
|
|
11
|
+
const threshold = typeof thresholdMs === 'number' && thresholdMs >= 0 ? thresholdMs : 100;
|
|
12
|
+
|
|
13
|
+
const slow = [];
|
|
14
|
+
for (const op of operations) {
|
|
15
|
+
if (typeof op.durationMs === 'number' && op.durationMs >= threshold) {
|
|
16
|
+
slow.push({
|
|
17
|
+
id: op.id,
|
|
18
|
+
name: op.name,
|
|
19
|
+
durationMs: op.durationMs,
|
|
20
|
+
thresholdMs: threshold,
|
|
21
|
+
status: op.status,
|
|
22
|
+
startTime: op.startTime,
|
|
23
|
+
endTime: op.endTime,
|
|
24
|
+
parentId: op.parentId,
|
|
25
|
+
depth: op.depth
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Sort descending by duration
|
|
31
|
+
return slow.sort((a, b) => b.durationMs - a.durationMs);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Builds a hierarchical tree from a flat list of operations.
|
|
36
|
+
*
|
|
37
|
+
* @param {Array<import('../core/operation').Operation>} operations
|
|
38
|
+
* @returns {Array<object>} Root nodes with nested children
|
|
39
|
+
*/
|
|
40
|
+
function buildOperationTree(operations = []) {
|
|
41
|
+
const opMap = new Map();
|
|
42
|
+
const roots = [];
|
|
43
|
+
|
|
44
|
+
// Create clean node clones
|
|
45
|
+
for (const op of operations) {
|
|
46
|
+
const raw = typeof op.toJSON === 'function' ? op.toJSON() : { ...op };
|
|
47
|
+
opMap.set(op.id, {
|
|
48
|
+
...raw,
|
|
49
|
+
children: []
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Connect parents and children
|
|
54
|
+
for (const op of operations) {
|
|
55
|
+
const node = opMap.get(op.id);
|
|
56
|
+
if (op.parentId && opMap.has(op.parentId)) {
|
|
57
|
+
opMap.get(op.parentId).children.push(node);
|
|
58
|
+
} else {
|
|
59
|
+
roots.push(node);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return roots;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = {
|
|
67
|
+
detectSlowOperations,
|
|
68
|
+
buildOperationTree
|
|
69
|
+
};
|